C++ operator+ 和 operator+= 重载

标签 c++ operator-overloading

我正在用 C++ 实现自己的矩阵类,以帮助我加深对该语言的理解。我在某处读到,如果您有一个有效的 += 运算符,请在您的 + 运算符中使用它。这就是我所拥有的:

template <class T>
const Matrix<T>& Matrix<T>::operator+(const Matrix<T> &R){

    Matrix<T> copy(*this);
    return copy += R;
}

这里是 += 运算符重载:

template <class T>
const Matrix<T>& Matrix<T>::operator+=(const Matrix<T> & second_matrix){
    //Learn how to throw errors....
    if (rows != second_matrix.getNumRows() || cols != second_matrix.getNumCols()){throw "Dimension mismatch.";}
    int i,j;
    for (i = 0; i < rows; i++){
        for (j = 0; j < cols; j++){
            data[i][j] += second_matrix.get(i,j);
        }
    }
    return *this;
}

我可以很好地使用 +=(例如,a += b;不返回任何错误)。但是调用 + 运算符(例如,a = b + c;)返回:

test.cpp.out(77055) malloc: *** error for object 0x300000004: pointer being freed was not allocated

为了完整起见,这是我的析构函数:

template <class T>
Matrix<T>::~Matrix(){
    for (int i = 1; i < rows; i++){
        delete[] data[i]; }
    delete[] data;
}

我断断续续地使用 C++ 几年了,但有时仍然无法跟踪指针。我希望这是正常的... 任何帮助都会很棒。谢谢!

编辑:这是我的复制构造函数。它被设置为释放数据数组,但我删除了它。现在我遇到了段错误。

template <class T>
Matrix<T>::Matrix(const Matrix<T>& second_matrix){

    rows = second_matrix.getNumRows();
    cols = second_matrix.getNumCols();
    data = new T*[rows];

    int i,j;
    for (i = 0; i < rows; i++){
        data[i] = new T[cols];
    }
    for (i = 0; i < rows; i++){
        for (j = 0; j < cols; j++){
            data[i][j] = second_matrix.get(i,j);
        }
    }

}

最佳答案

operator+() 不应返回引用类型,因为它是保存操作结果的新(本地声明的)实例。

关于C++ operator+ 和 operator+= 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4382440/

相关文章:

c++ - 单个共享内存中的不同类型

c++ - 转发声明一个类的 typedef 指针

c++ - operator<< 重载、 namespace 和模板

php - PHP 的 C++ 中的运算符重载等效,默认输出的 echo/print 类变量

c++ - 错误: ambiguous overload for 'operator<<'

c++ - std::shared_ptr 的用法

c++ - 移动一组共面点的简单程序不起作用

c++ - 从 C++ 程序在 Linux 上获取 SCSI 硬盘驱动器序列

c++ - 为什么在有私有(private)变量的情况下需要使引用常量?

c# - 为值类型实现 operator++ 的正确方法是什么?