gpt4 book ai didi

c++ - 实现模板 Matrix 类

转载 作者:行者123 更新时间:2023-11-30 01:51:29 25 4
gpt4 key购买 nike

假设我有以下代码:

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.

最佳答案

编译器警告您 most vexing parse .这一行:

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

被解析为名为 m3函数返回 Matrix<1,3> ,将一个没有参数的未命名函数作为参数并返回 Initializer .

你可以用额外的括号来修复它(根据编译器的建议):

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

关于c++ - 实现模板 Matrix 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26131986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com