cpp Const
常量函数(函数后加const)
class Text{
public:
void printconst(void) const{
cout<<"hello"<<endl;
}
void print(void){
cout<<"hello"<<endl;
}
private:
int k;
};
const Text a;
//上面定义了类Text的一常量对象
int main(void)
{
a.printconst(); //ok
a.print(); //error
//上面a.print()调用是非法的
return 0;
}
const对象只能调用const成员函数。
const对象的值不能被修改,在const成员函数中修改const对象数据成员的值是语法错误
在const函数中调用非const成员函数是语法错误
——————————————————————————————————————
任何不会修改数据成员的函数都应该声明为const类型。如果在编写const成员函数时,不慎修改了数据成员,或者调用了其它非const成员函数,编译器将指出错误,这无疑会提高程序的健壮性。
以下程序中,类stack的成员函数GetCount仅用于计数,从逻辑上讲GetCount应当为const函数。编译器将指出GetCount函数中的错误。
class Stack
{
public:
void Push(int elem);
int Pop(void);
int GetCount(void) const;//const成员函数
private:
int m_num;
int m_data[100];
};
int Stack::GetCount(void) const
{
++m_num; // 编译错误,企图修改数据成员m_num
Pop(); // 编译错误,企图调用非const函数
return m_num;
}
const成员函数的声明看起来怪怪的:const关键字只能放在函数声明的尾部,大概是因为其它地方都已经被占用了。
———————————————————————————————————
1。const 只能声名 member function
2。const member function 不能修改对象的任意成员
3。const member function 不能调用非 const member function
———————————————————————————————————
int a = 1;
int* const p = &a; //常量指针
p指向的地址不能改变,但p指向的地址里面的值是可以改变的。
比如*p = 2,这样a的值1就改变成2了。但不能p = &b;试图想把p指向变量b。

浙公网安备 33010602011771号