I was trying to learn some operator overloading methods on C++ then I had this error :
Error 7 error C2228: left of ‘.values’ must have class/struct/union
There is also another error that says :
Error 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;
}
Can someone tell me where I did wrong?
In the code you have posted,
sumis a pointer. Therefore, to access the members of the object, you need to use->:You also seem to be missing a semicolon after the declaration
Matrix<type> *sum;, but it’s unclear whether that is a transcription error or whether your code really looks like that.Finally, your memory management leaks an object. You allocate an object with
new, but return a copy of that object, and never free it. Perhaps you want something like: