jak*_*kev 9 c++ operator-overloading
我正在用c ++实现我自己的矩阵类,以帮助我培养对语言的理解.我读到某个地方,如果你有一个工作+ =运算符,在你的+运算符中使用它.这就是我所拥有的:
template <class T>
const Matrix<T>& Matrix<T>::operator+(const Matrix<T> &R){
Matrix<T> copy(*this);
return copy += R;
}
Run Code Online (Sandbox Code Playgroud)
这是+ =运算符重载:
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;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用+ =就好了(例如,a + = b;不返回任何错误).但是调用+运算符(例如,a = b + c;)会返回:
test.cpp.out(77055) malloc: *** error for object 0x300000004: pointer being freed was not allocated
Run Code Online (Sandbox Code Playgroud)
为了完整,这是我的析构函数:
template <class T>
Matrix<T>::~Matrix(){
for (int i = 1; i < rows; i++){
delete[] data[i]; }
delete[] data;
}
Run Code Online (Sandbox Code Playgroud)
我一直在使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*gen 22
operator+() 不应返回引用类型,因为它是保存操作结果的新(本地声明的)实例.