【发布时间】:2019-11-12 02:45:55
【问题描述】:
我可以在同一个班级中有两个像这样重载的operator[]吗?
当我使用operator[] 时,我对使用哪个定义感到困惑,int 不是模棱两可吗?他们不是有相同的签名吗?
template <class T, int n>
class ArrayTP
{
private:
T ar[n];
public:
ArrayTP() {};
virtual T & operator[](int i);
virtual T operator[](int i) const;
};
此类包含这些重载运算符的声明。不过,我的问题中没有包含定义。
【问题讨论】:
-
"他们不是有相同的签名吗?" 没有。一个是
const方法,另一个不是。 -
在
const方法中this是const。这不是正在发生的事情,但它应该足够接近以向您展示差异:T & operator[](int i)有点像T & operator[](ArrayTP * this, int i)和T operator[](int i) const有点像T operator[](const ArrayTP * this, int i)