我试图在 C++ 上学习一些运算符重载方法然后我遇到了这个错误:
错误 7 error C2228: '.values' 的左边必须有 class/struct/union
还有另一个错误说:
错误 4 error C2065: 'sum': undeclared identifier
Matrix<type> Matrix<type>::operator+(const Matrix& m){
if(num_of_rows != m.num_of_rows || num_of_cols != m.num_of_cols) // Checking if they don't have the same size.
Matrix<type> *sum;
sum = new Matrix<type>(num_of_rows, num_of_cols);
for(int i = 0; i < num_of_rows; i++)
for(int j = 0; j < num_of_cols; j++)
sum.values[i][j] = values[i][j] + m.values[i][j];
return *sum;
}
谁能告诉我哪里做错了?
最佳答案
在您发布的代码中,sum
是一个指针。因此,要访问对象的成员,需要使用->
。 :
sum->values[i][j] = ...
在声明 Matrix<type> *sum;
之后,您似乎还缺少一个分号,但不清楚这是转录错误还是您的代码看起来真的像那样。
最后,你的内存管理泄漏了一个对象。您使用 new
分配一个对象,但返回该对象的拷贝,并且永远不会释放它。也许你想要这样的东西:
Matrix<type> sum(num_of_rows, num_of_cols);
for ( ... )
sum.values[i][j] = ..
return sum;
关于c++ - 错误 C2228 : left of '.values' must have class/struct/union,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574766/