错误C2228:'.values'的左边必须有class / struct / union

时间:2012-05-13 19:59:44

标签: c++ sum overloading operator-keyword

我试图在C ++上学习一些运算符重载方法,然后我遇到了这个错误:

错误7错误C2228:'。values'的左边必须有class / struct / union

还有另一个错误:

错误4错误C2065:'sum':未声明的标识符

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;
}

有人可以告诉我哪里做错了吗?

1 个答案:

答案 0 :(得分:2)

在您发布的代码中,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;
相关问题