一个函数名字后有const,这个函数必定是成员函数,也就是说普通函数后面不能有const修饰,如:int print( ) const {.......} 这个函数必定为成员函数,即在类里面定义的函数。
在一个类里定义了一个const成员函数后,则此函数不能修改类中的成员变量,如果定义了一个类的const对象(非const对象可以调用const成员函数和非const成员hanshu ),它只能调用类中的const成员函数,如:
class text{
public:
void print_const(void) const { cout<<"hello"<<endl;} //有const修饰
void print(void) {cout<<"hello"<<endl;} //没有const修饰
void getk(void) const {k=5; } //错误,有const修饰,不能修改k的值,
private:
int k;
};
const text a;
int main()
{
a.print(); //错误,const对象只能调用
a.printf_const(); //正确
}
// void print() const {} 和 void print() {} 是重载函数,假如对象为const,则调用void print () const成员函数,如果为非const,则调用void print() ;
class text{
public:
void print(void) const {cout<<"hello_const"<<endl;}
void print(void) {cout<<"hello"<<endl;}
};
const text a;
int main()
{
a.print(); //屏幕输出 hello_const 假如对象a 定义为 text a,则输出 hello
return 0;
}