我为类A制作了"T operator[](int i)
const"和"T& operator[](int i)"。
(我也尝试了"const T&operator[](int i) const"和"T&operator[](int i)")
运算符打印一个值以区分调用哪个运算符。
A a;
int k = a[0];
k = a[0];
const int l = a[0];
结果:三次调用非常量版本。
如何调用常量版本?我应该使用常量类吗?没有机会调用一个 const 版本的函数而不使用 const 类?
您可以使用常量引用:
const A& b=a;
k=b[0];
或者一个常量演员表:
k=const_cast<const A&>(a)[0];