33,311
社区成员
发帖
与我相关
我的任务
分享
class A{
int a[10];
public:
A() {};
const int& operator [] (int index)const { return a[index]; }
int& operator [](int index) { return a[index]; }
};
int main() {
A a1;
const A a_const;
a1[1] = 5;
a_const[2] = 4;
system("pause");
return 0;
}
你试试就知道,a_const[2]是不能被修改的,如果去掉const的函数,a_const就不能调用普通函数了。
用const限定最重要的就是针对const的对象的一个特化,因为编译器只知道const的成员不能被修改,所以对于cosnt对象,非const的函数都不能使用
推荐你看一下《Effictive C++》