const成员函数、const类对象、mutable数据成员

1. const成员函数 只是告诉编译器,表明不修改类对象. 但是并不能阻止程序员可能做到的所有修改动作,比如对指针的修改,编译器可能无法检测到
2. 类体外定义的const成员函数,在定义和声明处都需要const修饰符
 1 class classname
 2 {
 3 public:
 4     classname() {}
 5     ~classname();
 6 
 7     void foo() const;
 8     char &operator[](int i);
 9 private:
10     //.
11 }
12 
13 void classname::foo() const
14 {
15 //
16 }
17 
18 char &classname::operator[](int i)
19 {
20 //..
21 }
22 int main()
23 {
24     const classname obj();
25     obj.foo();//ok
26     obj[2];//error,coz [] not const
27 }
28 

3. const对象为常量对象,它只能调用声明为const的成员函数。但是构造函数和析构函数是唯一不是const成员函数却可以被const对象调用的成员函数。 当然,一般对象当然也可以调用const成员了
 1 class A
 2 {
 3 public:
 4     A(int x, int y) : _x(x), _y(y) {}
 5     //int get() { return _x;}
 6     int get() const { return _y;}
 7 private:
 8     int _x, _y;
 9 };
10 
11 int main()
12 {
13     A obj(23);
14     const A obj1(23);
15     cout << obj.get() << " " << obj1.get();//3 3
16     
17     return 0;
18 }
19 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A
 5 {
 6 public:
 7     A(int x, int y) : _x(x), _y(y) {}
 8     int get() { return _x;}
 9     //int get() const { return _y;}
10 private:
11     int _x, _y;
12 };
13 
14 int main()
15 {
16     A obj(23);
17     const A obj1(23);
18     cout << obj.get() << " " << obj1.get();
19     //错误,obj1为常量对象,不能调用非const方法
20     return 0;
21 }

4. const成员函数可以被相同参数表的非const成员函数重载
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A
 5 {
 6 public:
 7     A(int x, int y) : _x(x), _y(y) {}
 8     int get() { return _x;}
 9     int get() const { return _y;}
10 private:
11     int _x, _y;
12 };
13 
14 int main()
15 {
16     A obj(23);
17     const A obj1(23);
18     cout << obj.get() << " " << obj1.get();
19     // 2  3
20     return 0;
21 }
22 

4. 为了允许修改一个类的成员变量,即使是一个const对象的数据成员,于是引入了mutable
通过将数据成员声明为mutable, 表明此成员总是可以被更新,即使在一个const成员函数中。

posted @ 2007-06-06 23:57  中土  阅读(4570)  评论(1编辑  收藏  举报
©2005-2008 Suprasoft Inc., All right reserved.