2010-10-07 36 views
0

我有这个奇怪的问题:当我的计划达成这个方法:有问题的矢量返回值 - 没有真正更新?

//Returns the transpose matrix of this one 
RegMatrix RegMatrix::transpose() const{ 
    RegMatrix result(numCol,numRow); 
    int i,j; 
    for(i=0;i<numRow;++i) 
     for(j=0;j<numCol;++j){ 
      result._matrix[j][i] = _matrix[i][j]; 
     } 

     return result; 
} 

突然崩溃......

,当我和我的VS调试运行它,它看起来只是所有优良,新的矩阵填充了相关的值,直到return result;从某个神秘的原因返回空矩阵向量。

我在哪里出错?


这里是我的拷贝构造函数的实现:

//CCtor of RegMatrix      
RegMatrix::RegMatrix(const RegMatrix &other): numRow(other.getRow()), numCol(other.getCol()){ 

    //Create 
    _matrix = vector<vector<MyDouble> >(other.getRow()); 
    int i,j; 
    for(i=0; i < numRow; i++) 
     _matrix[i] = vector<MyDouble>(other.getCol()); 

    //Copy Matrix 
    for(i=0;i<numRow; ++i){ 
     for(j=0;j<numCol; ++j){ 
      _matrix[i][j] = other._matrix[i][j]; 
     } 
    } 
} 

我的赋值操作符的实现:

//RegMatrix = RegMatrix 
RegMatrix& RegMatrix::operator=(const RegMatrix rhs){ 
    assert(numRow == rhs.getRow() && numCol == rhs.getCol()); 
    if(*this != rhs){ 
     int i,j; 
     for(i=0;i<numRow;++i) 
      for(j=0;j<numCol;++j){ 
       _matrix[i][j] = rhs._matrix[i][j]; 
      } 
    } 

    return *this; 
} 
+0

你的副本构造函数是什么样的? – 2010-10-07 22:48:32

+0

你的拷贝构造函数做了很多和不必要的拷贝(见PigBen的答案),但最终它应该工作。我能想象的代码是这样'RegMatrix换位= someMatrix.transpose();'所以接下来的犯罪嫌疑人是你的赋值运算符 – 2010-10-07 23:09:22

回答

0

假设MyDouble有一个正确的拷贝构造函数,你应该能够在您的拷贝构造函数降低到只此:

RegMatrix::RegMatrix(const RegMatrix &other):numRow(other.getRow()), numCol(other.getCol()), 
    _matrix(other._matrix) 
{ } 

看看,让你。

编辑: 如果列和行不相等,则您的赋值运算符可能会成为问题。你在那个例子中抛出一个断言,所以程序将会中止。那是你要的吗?你不是宁愿赋值改变列和行来匹配新的值吗?如果是这样,你可以这样做:

RegMatrix & RegMatrix::operator=(const RegMatrix & rhs) { 
    if(this == &rhs) 
     return *this; 
    numRow = rhs.getRow(); 
    numCol = rhs.getCol(); 
    _matrix = rhs._matrix; 
    return *this; 
} 
+0

它导致我一些更神秘的问题..我目前的CCtor有什么问题? – limlim 2010-10-07 23:14:26

+0

可能没有什么,它只是包含不必要的代码,所以它更容易出错。我只是想,如果你让你的构造更简单,你可以肯定这不是问题。看到亚历克斯的评论,我们现在需要看到你的任务运营商。如果你没有,那么我们需要看你的课堂体。 – 2010-10-07 23:19:42

+0

这是cc导致什么样的“更神秘的问题”? – 2010-10-07 23:32:37

0

您是按值返回矩阵。涉及拷贝构造函数。你的拷贝构造函数是如何定义的?

+0

RegMatrix的// CCtor \t \t \t \t RegMatrix :: RegMatrix(常量RegMatrix及其他):numRow行(其它.getRow()),numCol(other.getCol()){ \t //创建 \t _matrix = vector >(other.getRow()); \t int i,j; (i = 0; i (other.getCol()); \t //复制矩阵 \t为(I = 0;我 limlim 2010-10-07 22:50:37

+0

把这个问题放到你的问题中,请格式正确。 – 2010-10-07 22:52:03

+0

(我已经添加到我的问题,所以它会看起来更好) – limlim 2010-10-07 22:52:36