我正在用 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/