- const 修饰成员函数
成员函数后加const后我们称这个函数为常函数,它不可以修改成员属性, 关键字 mutable 修饰的成员属性例外
常函数表明自己不会对这个对象的数据成员(准确地说是非静态数据成员)作任何改变。
Hello(void)const;
- const 修饰对象:
声明对象前加 const 称该对象为常对象
常对象只能调用常函数。
例如:
class A
{
public:
void myfunc(void) const //const修饰成员函数,常函数
{
cout << "hello" << endl;
}
void myfunc2(void)
{
cout << "hello2" << endl;
}
};
int main()
{
const A a; //常对象,只能使用类中的常函数
a.myfunc();
a.myfunc2(); //错误
return 0;
}