簡體   English   中英

實現模板Matrix類

[英]Implementing a template Matrix class

假設我有以下代碼:

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;
}

而且我應該實現一個通用的Matrix,以使上述代碼得以編譯和工作。 在我當前的實現中,我遇到以下編譯錯誤,並且不確定我的錯誤在哪里:

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.

編譯器警告您最煩人的解析 這行:

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

被解析為名為m3函數 ,該函數返回Matrix<1,3> ,將不帶參數的未命名函數作為參數,並返回Initializer

您可以使用其他括號對其進行修復(如編譯器所建議):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM