使用模板重载运算符 ()

Overload operator () with templates

本文关键字:运算符 重载      更新时间:2023-10-16

我正在做一个需要使用模板完成的作业:这是一个矩阵类。

其中一个告诉我重载operator ()(int r, int c);,这样我就可以使用 obj(a, b); 访问我的数据或使用 obj(a, b)=100; 更改它。

我的课程的模板是template<class T, int C, int R>;然后我在公共范围内的班级内创建了 a:

T& operator()(int r, int c);//LINE 16

实现很简单。

我尝试了两种方式:

template <class T>
T& Matrix::operator()(int r, int c){
    return matrixData[r][c];
}
template <class T, int C, int R>
T& Matrix::operator()(int r, int c){ 
    return matrixData[r][c];
}

在最后一个中,我收到错误告诉我:

16: Error: expected type-specifier before '(' token

上面的第 16 行有一个注释错误:

no 'T& Matrix<T, C, R>::operator()(int, int)' member function declared in class 'Matrix<T, C, R>'

该类template<class T, int C, int R> class Matrix {...}

以下内容对我有用:

#include <iostream>
template<typename T, int R, int C>
class Matrix {
  T data[R][C];
public:
  T& operator()(int r, int c);
};
template <typename T, int R, int C>
T& Matrix<T, R, C>::operator()(int r, int c) {
  return data[r][c];
}
int main() {
  Matrix<int, 3, 4> m;
  m(0, 1) = 42;
  std::cout << m(0, 1) << std::endl;
}
如果我

理解正确,您缺少Matrix上的类型:

template <class T>
T& Matrix<T>::operator()(int r, int c){
    return matrixData[r][c];
}
template <class T, int C, int R>
T& Matrix<T>::operator()(int r, int c){ 
    return matrixData[r][c];
}