为什么'没有可行的操作员超载'?

为什么'没有可行的操作员超载'?

问题描述:

我正在写的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'类型我做错了什么,以及如何解决它?

PS。 XCode 7,如果这很重要。

+6

你应该使用这个? – tkausl

+2

这个作品:http://coliru.stacked-crooked.com/a/841cd49502f05fe9 –

+0

@ m.s。嗯,它是一个编译器相关的问题? – alekscooper

此功能:

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

不能被称为是这样的:

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

由于非const引用文字无法拍摄。引用允许修改,以及修改3意味着什么?为什么你把int值作为参考

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