const修饰虚函数

【1】程序1

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base
 5 {
 6 public:
 7     virtual void print() const = 0;
 8 };
 9 
10 class Test : public Base
11 {
12 public:
13     void print();
14 };
15 
16 void Test::print()
17 {
18     cout << "Test::print()" << endl;
19 }
20 
21 void main()
22 {
23     // Base* pChild = new Test(); //compile error!
24     // pChild->print();
25 }

【2】程序2

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base
 5 {
 6 public:
 7     virtual void print() const = 0;
 8 };
 9 
10 class Test : public Base
11 {
12 public:
13     void print();
14     void print() const;
15 };
16 
17 void Test::print()
18 {
19     cout << "Test::print()" << endl;
20 }
21 
22 void Test::print() const
23 {
24     cout << "Test::print() const" << endl;
25 }
26 
27 void main()
28 {
29     Base* pChild = new Test();
30     pChild->print();
31 }
32 /*
33 Test::print() const
34 */

【3】程序3

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base
 5 {
 6 public:
 7     virtual void print() const = 0;
 8 };
 9 
10 class Test : public Base
11 {
12 public:
13     void print();
14     void print() const;
15 };
16 
17 void Test::print()
18 {
19     cout << "Test::print()" << endl;
20 }
21 
22 void Test::print() const
23 {
24     cout << "Test::print() const" << endl;
25 }
26 
27 void main()
28 {
29     Base* pChild = new Test();
30     pChild->print();
31 
32     const Test  obj;
33     obj.print();
34 
35     Test obj1;
36     obj1.print();
37 
38     Test* pOwn = new Test();
39     pOwn->print();
40 }
41 
42 /*
43 Test::print() const
44 Test::print() const
45 Test::print()
46 Test::print()
47 */

备注:一切皆在代码中。

总结:const修饰成员函数,也属于函数重载的一种范畴。

Good Good Study,  Day  Day  Up.

顺序  选择  循环  总结

posted @ 2014-03-24 23:06  kaizenly  阅读(2961)  评论(0编辑  收藏  举报
打赏