我写了一堂课,我在添加矩阵时遇到了问题。我知道我必须重载运算符 +,但我不知道具体如何。有任何想法吗 ?
class CMatrix
{
private:
int Rows;
int Columns;
float* pData;
public:
CMatrix(void);
CMatrix(int rows, int columns);
void setElement(int row, int column, float element);
float getElement(int row, int column);
...};
istream& operator>>(istream& in, CMatrix& matrix)
{
in >> matrix.Rows;
in >> matrix.Columns;
for(int i = 0; i < matrix.Rows; i++)
for(int j = 0; j < matrix.Columns; j++)
in >> *(matrix.pData + i * matrix.Columns + j);
return in;
}
CMatrix::CMatrix(int rows, int columns)
{
Rows = rows;
Columns = columns;
pData = new float[Rows * Columns];
float* pEnd = &pData[Rows * Columns];
for(float* p = pData; p < pEnd; p++)
*p = 0.0;
}
void CMatrix::setElement(int row, int column, float element)
{
*(pData+ row * Columns + column) = element;
}
float CMatrix::getElement(int row, int column)
{
return *(pData + row * Columns + column);
}
我重载了运算符 '<<' ,'>>' ,但是运算符 + 有问题。
不幸的是,我的声望不到 10……所以如果我写:
CMatrix operator+(const CMatrix &lhs, const CMatrix &rhs)
{
Cmatrix result (Rows,Columns);
for(int i=0; i <Rows ; i++)
for( int j=0; j<Columns; j++)
result.setElement(i,j) = lhs.getElement(i,j) + rhs.getElement(i,j);
return result;
}
int main()
{
const int n = 10, m = 5;
CMatrix m1(n, m);
CMatrix m2(n, m);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
m1.setElement(i, j, (float)(i * m + j));
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
m2.setElement(i, j, (float)(i * m + j));
cout<<m1+m2; // it doesn't work
Thanks all for help, i did it at last...