-1

我試圖用重載運算符+添加兩個二維矩陣時出現問題。我已經成功地將這兩個矩陣分配給了兩個不同的數組。重載運算符+ C++的錯誤

我的錯誤是:

在功能`mathadd ::矩陣mathadd ::運算符+(mathadd ::矩陣&,mathadd ::矩陣&)「:

呼叫沒有匹配功能`mathadd ::矩陣::矩陣(雙&)」

候選是:mathadd ::矩陣::矩陣(常量mathadd ::矩陣&)

在我INT的main(){}這個錯誤的主要部分是:

matrices sample; 
double array1[4][4], array2[4][4], add[4][4]; 
add[4][4] = array1[4][4] + array2[4][4]; 

重載運算符的定義是:

 matrices operator +(matrices& p1, matrices& p2) 
     { 
      double addition[4][4]; 
      for (int y = 0; y < 4; ++y) 
      { 
       for (int x = 0; x < 4; ++x) 
       { 
        addition[4][4] = p1.get_array1() + p2.get_array2(); 
       } 
      } 
      matrices sum(addition[4][4]); // This is where the error is. 
      return sum; 
     } 

我的類看起來像這樣

class matrices 
    { 
     public: 
       matrices(); 
       void assignment(double one[4][4], double two[4][4]); 
       double get_array1() const {return first_array[4][4];} 
       double get_array2() const {return second_array[4][4];} 
       matrices operator +(matrices& p1, matrices& p2); 
     private: 
       double first_array[4][4], second_array[4][4]; 
       //Initialized to 0 in constructor. 
    }; 

我不下站在這個錯誤意味着什麼,我將不勝感激任何幫助理解它的意思,以及我如何解決它。

+2

你需要學習基本陣列操作和基本的C++在開始重載操作符之前。學習在運行之前進行爬網。更實際的是,編寫一個添加兩個矩陣並返回結果的函數「add」:在超載操作員之前,您的問題還遠遠不夠。 – Yakk

回答

3

addition[4][4]是一個雙出界數組訪問,從addition命名的第五個double[]獲得第五個double。只需通過名稱addition而不是addition[4][4]matrices sum(addition[4][4])

所以應該

matrices sum(addition); 
return sum; 

那只是你的編譯器錯誤的根源。你的代碼中也有許多邏輯錯誤,比如我之前提到的超出範圍的數組訪問,在內部for -loop中。你將不得不解決這些問題,否則會得到未定義的行爲。

+0

我已經嘗試過,它沒有工作。我得到和以前一樣的錯誤。 – Titan

1

您會收到錯誤消息,因爲您的operator +是爲matrices類型的對象定義的,而不是針對double s的二維數組。您需要在添加矩陣之前構建矩陣,如下所示:

首先,爲matrices添加一個構造函數,其中需要double[4][4]。然後,更改operator +的簽名是static,並採取const參照其參數:

static matrices operator +(const matrices& p1, const matrices& p2); 

現在你可以這樣寫:

matrices add = matrices(array1) + matrices(array2);