c++ - 错误 C2228 : left of '.values' must have class/struct/union

标签 c++ sum overloading operator-keyword

我试图在 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/

相关文章:

MYSQL Sum 一次计算的结果

C++ - 关于函数模板实例化的规则

c++ - 不同头文件中跨相同命名空间的 typedef

excel - SUMPRODUCT( SUMIF() ) - 这是如何工作的?

MYSQL 对于过滤的行返回 0

类的 C++ 函数重载

c++ - STL 算法 : Why no additional interface for containers (additional to iterator pairs)?

c++ - 如何使用可变模板来包装可变数量的函数参数?

c++ - WM_COMMAND 未传递到主窗口

c++ - com 对象和接口(interface)