Note
- 常量对象上可以执行常量成员函数,是因为常量成员函数确保不会修改任何非静态成员变量的值。
- 编译器如果发现常量成员函数内出现了有可能修改非静态成员变量的语句,就会报错。
- 因此,常置成员函数内部也不允许调用类的其他非常置成员函数(静态成员函数除外)。
- 在您可能犯这类错误时,IDE可能会提示您!
#include <iostream>
using namespace std;
class Sample
{
int a;
public:
Sample() : a(-1) {}
void GetValue() const;
void test();
void testConst() const;
};
void Sample::GetValue() const
{
cout << "GetValue() const member function was called!@" << endl;
cout << "obj.a=" << a << endl;
}
void Sample::test()
{
cout << "test() was called!" << endl;
cout << "obj.a=" << a << endl;
};
void Sample::testConst() const
{
cout << "testConst() was called!" << endl;
cout << "obj.a=" << a << endl;
};
int main()
{
const Sample obj;
obj.GetValue();
obj.testConst();
return 0;
}