2013-04-27 96 views
-1

我有一個類項目是在動態對象上進行操作。 我有一個叫Matrix的類,它使用2維指針數組來存儲Complex類型的對象(這是一個複數類)。我需要能夠通過將數組中的所有值添加到一起並返回一個新數組來添加2個數組。問題是我不明白訪問數組中每個Complex對象的語法。以下是我迄今爲止的重載加法運算符:添加二維動態數組

const Matrix Matrix::operator+(const Matrix& rhs) const 
{ 
    Matrix newMatrix(mRows,mCols); 
    for(int i=0;i<mRows;i++) 
    { 
     for(int j=0;j<mCols;j++) 
     { 
      (*newMatrix.complexArray[i]) = (*complexArray[i])+ (*rhs.complexArray[i]); 
     } 
    } 

return newMatrix; 
} 

下面是Matrix對象重載輸入操作符:

istream& operator>>(istream& input, Matrix& matrix) 
{ 
bool inputCheck = false; 
int cols; 

while(inputCheck == false) 
{ 
    cout << "Input Matrix: Enter # rows and # columns:" << endl; 

    input >> matrix.mRows >> cols; 
    matrix.mCols = cols/2; 

    //checking for invalid input 
    if(matrix.mRows <= 0 || cols <= 0) 
    { 
     cout << "Input was invalid. Try using integers." << endl; 
     inputCheck = false; 
    } 
    else 
    { 
     inputCheck = true; 
    } 

    input.clear(); 
    input.ignore(80, '\n'); 
} 

if(inputCheck = true) 
{ 
    cout << "Input the matrix:" << endl; 

    for(int i=0;i< (matrix.mRows+matrix.mCols);i++) 
    { 
     Complex* newComplex = new Complex(); 
     input >> *newComplex; 
     matrix.complexArray[i] = newComplex; 
    } 
} 
return input; 
} 

這裏是矩陣類定義:

​​

和構造函數:

Matrix::Matrix(int r, int c) 
{ 
if(r>0 && c>0) 
{ 
    mRows = r; 
    mCols = c; 
} 
else 
{ 
    mRows = 0; 
    mCols = 0; 
} 

if(mRows < MAX_ROWS && mCols < MAX_COLUMNS) 
{ 
    //complexArray= new Complex[mRows]; 
    complexArray= new Complex*[mRows]; 

    for(int i=0;i<mRows;i++) 
    { 
     complexArray[i] = new Complex[mCols]; 
    } 
} 
} 

現在,程序編譯,但在運行時添加矩陣時停止工作。如果有人能告訴我我應該使用什麼語法,爲什麼,這將是非常有用的。

回答

0

你似乎沒有足夠的投入。你將(複數)列作爲輸入,但是試圖(正確地)在矩陣內迭代(行*列)元素。

for(int i=0;i< (matrix.mRows+matrix.mCols);i++) 

for(int i=0;i<mRows;i++) 
    { 
     for(int j=0;j<mCols;j++)