2012-02-03 79 views
1

我想做一个例子(只是例子!我知道它泄漏)的应用程序来学习运算符在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; 
} 
+0

我没有在那里看到析构函数。你违反[三条规则](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree)? – 2012-02-03 14:49:43

+0

我不知道为什么这不起作用,但有两件事情脱颖而出。这段代码泄露了整个地方的内存。它应该有一个析构函数来清理内存,甚至更好,它应该使用智能指针来管理内存。你也是一个整数。抛出一个类最好的做法是,最好是从std :: exception派生出一个类。 – mcnicholls 2012-02-03 14:54:29

回答

5
Matrix::Matrix(int row, int col){ 
    nrow = row; 
    ncol = ncol; 
    data = new float[nrow*ncol]; 
} 

有一个错字在那里,有不确定的行为在你的代码。

与修复:

ncol = col; 

(确保你把你编译器警告/诊断级别设为最大,GCC抓住这一点)

你泄露你的float[]太,所以你代码不完整。不要忘记添加适当的析构函数,并始终遵循rule of three