【发布时间】:2012-02-26 04:17:36
【问题描述】:
我正在尝试制作一个示例(只是示例!我知道它会泄漏)应用程序来学习 C++ 中的运算符重载,但我得到的总和元素的值为零......我怀疑问题出在是 int 复制构造函数。
具体实现如下:
class Matrix{
public:
Matrix(int row, int col);
Matrix(const Matrix& src);
float& set(int row, int col);
float get(int row, int col);
const Matrix & operator+(const Matrix& rhs);
private:
float* data;
int nrow;
int ncol;
};
Matrix::Matrix(int row, int col){
nrow = row;
ncol = ncol;
data = new float[nrow*ncol];
}
Matrix::Matrix(const Matrix& src){
nrow = src.nrow;
ncol = src.ncol;
data = new float[nrow*ncol];
for(int i = 0; i < nrow*ncol; i++){
data[i] = src.data[i];
}
}
float& Matrix::set(int row, int col){
return data[row*ncol+col];
}
float Matrix::get(int row, int col){
return data[row*ncol+col];
}
const Matrix & Matrix::operator+(const Matrix& rhs){
if (this->nrow == rhs.nrow && this->ncol == rhs.ncol){
Matrix* m = new Matrix(rhs.nrow, rhs.ncol);
for(int i=0; i< nrow*ncol; i++){
m->data[i] = data[i] + rhs.data[i];
}
return *m;
} else {
throw -1;
}
}
#include <iostream>
using namespace std;
int main ()
{
Matrix A(1,1);
Matrix B(1,1);
A.set(0,0)=1;
B.set(0,0)=2;
cout << A.get(0,0) << endl;
cout << B.get(0,0) << endl;
Matrix C = A + B; // Marix C(A+B);
cout << C.get(0,0) << endl;
return 0;
}
【问题讨论】:
-
我没有在其中看到析构函数。你违反the rule of three了吗?
-
我不确定为什么这不起作用,但有两件事很突出。此代码到处泄漏内存。它应该有一个析构函数来清理内存,或者更好的是,它应该使用智能指针来管理内存。你也在抛出一个int。最好的做法是抛出一个类,最好是从 std::exception 派生的类。
标签: c++ matrix operators operator-overloading