以下代码的输出结果是什么?

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class A
 6 {
 7 protected:
 8     int m_data;
 9 
10 public:
11     A(int data = 0)
12     {
13         m_data = data;
14     }
15     int GetData()
16     {
17         return doGetData();
18     }
19 
20     virtual int doGetData()
21     {
22         return m_data;
23     }
24 };
25 
26 class B: public A
27 {
28 protected:
29     int m_data;
30 
31 public:
32     B(int data = 1)
33     {
34         m_data = data;
35     }
36 
37 
38     int doGetData()
39     {
40         return m_data;
41     }
42 };
43 
44 
45 class C: public B
46 {
47 protected:
48     int m_data;
49 
50 public:
51     C(int data = 2)
52     {
53         m_data = data;
54     }
55 
56 };
57 
58 int main()
59 {
60     C c(10);
61 
62     cout << c.GetData()<<endl;
63     cout << c.A::GetData()<<endl;
64     cout << c.B::GetData()<<endl;
65     cout << c.C::GetData()<<endl;
66     cout << c.doGetData()<<endl;
67     cout << c.A::doGetData()<<endl;
68     cout << c.B::doGetData()<<endl;
69     cout << c.C::doGetData()<<endl;
70 
71     cout<<endl;
72     system("pause");
73 
74     return 0;
75 }

输出

1

1

1

1

1

0

1

1

 

注意就近调用,如果父辈存在相关接口则优先调用父辈接口,如果父辈也不存在相关接口则调用祖父辈接口。

posted @ 2012-08-13 23:01  wolenski  阅读(824)  评论(0编辑  收藏  举报