我正在编写一个二维数组类并尝试重载运算符 []:
typedef unsigned long long int dim;
template<typename N>
class Array2D {
private:
dim _n_rows;
dim _n_cols;
vector<vector<N>> M;
public:
dim n_rows() { return _n_rows; }
dim n_cols() { return _n_cols; }
Array2D(): _n_rows(0), _n_cols(0), M(0, vector<N>(0)){}
Array2D (const dim &r, const dim &c) : _n_rows(r), _n_cols(c), M(r, vector<N>(c)) {}
void set(const dim &i, const dim &j, const N &elem) { M[i][j] = elem; } // Works fine
vector<N>& operator[](int &index) { return M[index]; } // <- PROBLEM
};
Run Code Online (Sandbox Code Playgroud)
我的看法是:操作符 [] 返回一些东西(向量),而后者又具有重载的操作符 []。这就是为什么我认为
Array2D<int> L(10, 10);
L[3][3] = 10;
Run Code Online (Sandbox Code Playgroud)
应该管用。
显然,编译器不这么认为,说'没有可行的重载运算符 [] 类型'Array2D'我做错了什么以及如何解决它?
附注。XCode 7,如果这很重要。
这个功能:
vector<N>& operator[](int &index)
Run Code Online (Sandbox Code Playgroud)
不能这样调用:
Array2D<int> L(10, 10);
L[3][3] = 10;
Run Code Online (Sandbox Code Playgroud)
因为不能采用对文字的非常量引用。引用允许修改,修改意味着什么3?
你应该改用这个:
vector<N>& operator[](size_t index)
Run Code Online (Sandbox Code Playgroud)