为什么是“没有可行的操作员过载”

Why is 'No viable operator overload'?

本文关键字:操作员 为什么      更新时间:2023-10-16

我正在编写一个 2D 数组类并尝试重载运算符[]:

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

我看到它的方式:运算符 [] 返回一些东西(向量),而它又具有重载的运算符 []。这就是为什么我认为

Array2D<int> L(10, 10);
L[3][3] = 10;

应该工作。

显然,编译器不这么认为,说"对于类型'Array2D'没有可行的重载运算符[]"我做错了什么以及如何解决它?

附言XCode 7,如果这很重要的话。

此函数:

vector<N>& operator[](int &index)

不能这样称呼:

Array2D<int> L(10, 10);
L[3][3] = 10;

因为不能采用对文字的非常量引用。 引用允许修改,修改3意味着什么?

您应该改用它:

vector<N>& operator[](size_t index)