函数后面加const
编译器会自动给每一个函数加一个this指针。在一个类的函数后面加上const后,就表明这个函数是不能改变类的成员变量的(加了mutable修饰的除外,后面有讲)。实际上,也就是对这个this指针加上了const修饰。
- #include <iostream>
- using namespace std;
- class CTest
- {
- public:
- void show() const
- {
- cout << "const" << endl;
- }
- void show()
- {
- cout << "normal" << endl;
- }
- };
- int main()
- {
- CTest a;
- a.show();
- const CTest b;
- b.show();
- system("pause");
- return 0;
- }
显示结果:normal
const
a对象将调用普通show(),b对象将调用show() const。
如果注释掉 void show() const 该成员函数,b.show()将报错。
如果注释掉void show(),程序可以正常运行,因为a.show()调用时,会将其this指针上加const