const对象只能调用const成员函数,而非const对象可以调用const或非const成员函数。例如:

const对象
1 class A
2 {
3  public:
4 A(int i = 0):mI(i){}
5 int getI() const {return mI;}
6 void f(){}
7 void setI(int i) {mI = i;}
8  private:
9 int mI;
10 };
11
12  int main (int argc, char** argv)
13 {
14 const A ca;
15 ca.getI(); //ok
16 //ca.setI(1); //ERROR
17 //ca.f(); //ERROR
18  
19 A a;
20 a.getI(); //ok
21   a.setI(1); //ok
22 a.f(); //ok
23
24 return 0;
25 }
26

上面的例子可以看出,即使非const成员函数f()没有改变对象的状态(属性),const成员也无法调用。

posted on 2010-03-21 21:03  cppfans  阅读(185)  评论(0编辑  收藏  举报