实现一个模板矩阵类
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;
}
我应该实现一个通用的矩阵来编译和工作上面的代码。在我目前的实现中,我有以下编译错误,我不确定我的错误在哪里:
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()));
相关文章:
- 实现一个在集合上迭代的模板函数
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如何为位集找到/实现一个好的哈希函数
- C++哈希表中,两个相同的实现,但一个给出错误
- 如何将这两个函数组合成一个实现?
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 为什么这个快速排序实现给出了一个奇怪的输出
- C++:实现一个全局常量,其值由用户给出
- C++:实现一个接收lambda作为输入的高阶函数
- std::sort 一个实现了移动构造函数的类
- GMock - 用另一个实现模拟抽象类
- 有没有办法(C++)创建一个实现某些功能的模板类?
- 创建一个实现选项卡并可用作 QMainWindow 中的"central widget"的类
- 说出一个实现STL兼容序列容器的好指南)
- 一个C++实现的隐马尔可夫模型林安装错误
- 一个实现是否允许在同一地址放置两个相同的函数定义