zhiyinjixu

  博客园  :: 首页  ::  :: 联系 ::  :: 管理

const成员函数

①、const成员函数中不能对数据成员进行修改;
②、const成员函数中不能调用非const成员函数;
③、const成员函数中可以调用非const的非成员函数。

注意:
①一般将不修改数据成员的成员函数都定义为const成员函数,只是一种习惯;
②const函数只能是成员函数,一般函数是不能给加const,如:
f() const {}
int main () {}
这就是错误的,因为const函数是对类中的成员函数而言的。

 

void f4()  { } 
class A
{
public:
    int x;   
  void f1() {}
  void f2() const ;  //const成员函数      
  void f3() const {} ;
} ;
void A::f2 () const
{
 ++x;   //错误,说明①
 f1();  //错误,说明②
f3();  //正确,说明②
f4();  //正确,说明③
}

 

 

 

 

 

 

 

 

 

posted on 2011-11-14 16:22  zhiyinjixu  阅读(144)  评论(0)    收藏  举报