2014-09-30 77 views
1

假設我有以下代碼:實現一個模板Matrix類

int main(){ 

    class Initializer { 
    public: 
     double operator()(int i, int j) const { 
      return i + j; 
     } 
    }; 
    Matrix<2,5> m1; 
    Matrix<2,5> m2(7); 
    Matrix<1,3> m3(Initializer()); 

    m1(2,3) = 6; 
    m2 += m1; 
    Matrix<2,5> m4 = m1 + m2; 
    return 0; 
} 

我應該實現一個通用的矩陣,使上面的代碼編譯和工作。 以我目前的執行情況我有以下編譯錯誤,我不知道哪裏是我的錯誤:

template <int R, int C> 
class Matrix { 
private: 
    double matrix[R][C]; 
public: 
    //C'tor 
    Matrix(const double& init = 0){ 
     for (int i = 0; i < R; i++){ 
      for (int j = 0; j < C; j++){ 
       matrix[i][j] = init; 
      } 
     } 
    } 

    Matrix(const Initializer& init) { 
     for (int i = 0; i < R; i++){ 
      for (int j = 0; j < C; j++){ 
       matrix[i][j] = init(i,j); 
      } 
     } 
    } 

    //Operators 
    double& operator()(const int& i, const int& j){ 
     return matrix[i][j]; 
    } 

    Matrix<R,C>& operator=(const Matrix<R,C>& otherMatrix){ 
     for (int i = 0; i < R; i++){ 
      for (int j = 0; j < C; j++){ 
       matrix[i][j] = otherMatrix.matrix[i][j]; 
      } 
     } 
     return *this; 
    } 

    Matrix<R,C>& operator+=(const Matrix<R,C>& otherMatrix){ 
     for (int i = 0; i < R; i++){ 
      for (int j = 0; j < C; j++){ 
       matrix[i][j] = otherMatrix.matrix[i][j] + matrix[i][j]; 
      } 
     } 
     return *this; 
    } 

    Matrix<R,C> operator+(const Matrix<R,C>& otherMatrix) const { 
     Matrix<R,C> newMatrix; 
     newMatrix = otherMatrix; 
     newMatrix += *this; 
     return newMatrix; 
    } 
}; 

q3.cpp:68:16: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse] 
     Matrix<1,3> m3(Initializer()); 
         ^~~~~~~~~~~~~~~ 
q3.cpp:68:17: note: add a pair of parentheses to declare a variable 
     Matrix<1,3> m3(Initializer()); 
        ^
         (   ) 
1 warning generated. 
Doppelganger:ex4_dry estro$ g++ q3.cpp 
q3.cpp:68:16: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse] 
     Matrix<1,3> m3(Initializer()); 
         ^~~~~~~~~~~~~~~ 
q3.cpp:68:17: note: add a pair of parentheses to declare a variable 
     Matrix<1,3> m3(Initializer()); 
        ^
         (   ) 
1 warning generated. 
+0

這是C++語法的怪異之一。正如編譯器告訴你的,你沒有像你可能想要的那樣調用'Initializer'的構造函數。 – 5gon12eder 2014-09-30 23:47:57

+3

什麼阻止你實際閱讀這些診斷? – 2014-09-30 23:54:46

回答

4

編譯器會警告你的most vexing parse。這條線:

Matrix<1,3> m3(Initializer()); 

被解析功能命名m3返回一個Matrix<1,3>,以作爲一個參數不帶參數的匿名函數並返回一個Initializer

可以用額外的括號修復它(由編譯器爲決定):

Matrix<1,3> m3((Initializer()));