2014-02-18 45 views
0

該類由存儲動態二維數組的對象'mPoint'組成。我試圖讓它可以比較這些矩陣中的兩個,看看它們是否相等。因此我重載了運算符'=='。運算符重載:不匹配'運算符[]'

我得到一個錯誤「操作符[]'(操作數類型是'Square_Matrix和'int')指向行」if(mPoint [i] [j]!= Par [i] [j])」在.cpp文件。我怎樣才能解決這個問題?我很新的超載

//header file 
#include <iostream> 
using namespace std; 

class Square_Matrix 
{ 
public: 
    int **mPoint; 
    int size; 
    void Set_Size (int new_size); 
    bool operator==(Square_Matrix Par); 

//.cpp file 
#include <iostream> 
using namespace std; 
#include "Square_Matrix.h" 

void Square_Matrix::Set_Size (int new_size) 
{ 
    for (int i = 0; i < size; i++){ 
     delete [] mPoint[i]; 
    } 
    delete [] mPoint; 

    size = new_size; 
    mPoint = new int*[new_size]; 
    for (int i = 0; i < new_size; i++){ 
     mPoint[i] = new int[new_size]; 
    } 
} 

bool Square_Matrix::operator==(Square_Matrix Par){ 
    if (size != Par.size){ 
     return false; 
    } 
    for (int i = 0; i < size; i++){ 
     for (int j = 0; j < size; j++){ 
      if (mPoint[ i ][ j ] != Par[ i ][ j ]){ 
       return false; 
      } 
     } 
    } 
    return true; 
} 
+0

請顯示你的重載'運算符的定義[]' – Brian

+0

如果你還沒有定義一個,那麼這就是爲什麼你會得到一個錯誤。 – Brian

回答

1

在這裏你有你的問題,在這條線if (mPoint[ i ][ j ] != Par[ i ][ j ]){ 你直接試圖在Square_Matrix的實例上應用運算符[][]。這就是爲什麼編譯器說「不匹配'操作符[]'」

您應該使用類似if (mPoint[ i ][ j ] != Par.mPoint[ i ][ j ]){的東西來解決此問題。我認爲它是一個錯字。

最好通過const Square_Matrix&作爲參數。 在你的頭文件更改operator==簽名, bool operator==(const Square_Matrix& Par);

和CPP文件

bool Square_Matrix::operator==(const Square_Matrix& Par) 
{ 
    // your logic. 
} 
+0

這工作,非常感謝 – Foxic

+1

請注意,您的操作員編寫的方式,你每次打電話都複製班級 - 這會減慢你的應用程序。將簽名更改爲const ref要好得多。 –

+0

@Foxic - 不要在你的'operator =='函數中傳值。這將給@Peter R提到的問題,它更好地改變你的參數爲'const Square_Matrxi&Par' –

1

最簡單的解決辦法是改變你的operator==()如下:

bool Square_Matrix::operator==(const Square_Matrix& Par){ 
    if (size != Par.size){ 
     return false; 
    } 
    for (int i = 0; i < size; i++){ 
     for (int j = 0; j < size; j++){ 
      if (mPoint[ i ][ j ] != Par.mPoint[ i ][ j ]){ 
       return false; 
      } 
     } 
    } 
    return true; 
} 

你方陣類有沒有operator[]()。同樣,因爲這是一個類成員函數,所以你可以訪問Square_Matrix輸入參數的私有成員 - 所以直接使用它們。最後,你應該使它成爲避免複製的參考,但這也意味着你想要阻止更改,因此使它成爲const引用。

+0

錯誤:'布爾Square_Matrix :: operator ==(const Square_Matrix&)'的原型不匹配類'Square_Matrix '////錯誤:應聘者是:bool square_Matrix :: operator ==(Square_Matrix) – Foxic

+0

您需要更改頭文件以匹配新簽名。 –