首页 > 解决方案 > 如何从模板类中重载创建的指针对象上的运算符?

问题描述

我创建了一个以 Matrix 命名的模板类。我试图弄清楚如何为指向 Matrix 对象的指针实现 operator+ 重载。我的对象是标量矩阵运算。我想为矩阵上的每个单元格添加一个整数值。我无法理解我的代码发生了什么。模板让我很困惑。

“m1”是我的矩阵对象。当我使用m1 = m1+2时,我收到分段错误错误。

我尝试了许多不同的组合,但我总是遇到同样的错误。

Matrix <int> * m = new Matrix <int> (10,10,2)
return m;

我的矩阵类:

template <typename T> 
class Matrix{
    vector< vector<T> > matris;
public: 
    Matrix(); // 10x10 matrix with zeros
    Matrix(int width, int height, int value); 
    void print();

    Matrix* operator+(T value){
        return (new Matrix<int>(10,10,2)); // 10x10 matrix filled with 2
    }
};

我的主要功能:

int main(){
    Matrix <int> *m1 = new Matrix <int>(); // 10x10 matrix with zeros
    m1->print(); // it succesfully shows the elements
    m1 = m1 + 2; // whenever I tried this, I get "Segmentation Fault"
    m1->print();

    return 0;
}

我的 print() 函数:

template <typename T> 
void Matrix<T>::print(){
    for(int h=0; h<matris.size(); h++){
        for(int w=0; w<matris[0].size(); w++){
            printf("%4d", matris[h][w]);
        }
        cout << endl;
    }
}

输出:

   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
Segmentation fault

我的期望是分配成功,但我收到分段错误错误。我在这里做错了什么?

标签: c++

解决方案


当你使用

 m1 = m1 + 2;

operator+不使用重载的。那只是指针算术。之后,m1指向你不拥有的内存。访问 after 的成员m1会导致未定义的行为。

您可以通过使用在语法上修复它

 m1 = *m1 + 2;

但它有自己的问题。当你这样做时,原来m1指向的内存会丢失到你的程序中。你有内存泄漏。

提供重载为

Matrix* operator+(T value) { ... }

不是惯用的。也许您想使用:

Matrix operator+(T const& value) const { ... }

更好的选择是使用几个非成员函数重载:

Matrix operator+(Matrix const& m, T const& value);
Matrix operator+(T const& value, Matrix const& m);

有了它,您可以使用:

Matrix<int> m1;
Matrix<int> m2 = m1 + 10;
Matrix<int> m3 = 30 + m1;

有关运算符重载的更多信息,请参见运算符重载的基本规则和习惯用法是什么?


推荐阅读