# Include <iostream> using namespace STD; Class A {protected: int m_data; public: A (int data = 0) {m_data = data;} int getdata () {return dogetdata () ;}virtual int dogetdata () {return m_data;/* m_data = 0 * //} // interface, if not called directly, then, call the derived class to implement his function}; Class B: Public A {protected: int m_data; public: B (INT DATA = 1) {m_data = data ;} // here m_data = 0 in a and m_data = 1 int dogetdata () {return m_data;/* m_data = 1 * // implementation interface}; Class C: public B // C inherits the methods and attributes of Class A and Class B, and does not define the new interface. Therefore, the interface is also defined in Class B {protected: int m_data; public: C (int data = 2) {m_data = data;} // here m_data = 0 in a, m_data = 1 in B, m_data = 2} in C Class; int main () {C (10); cout <C. getdata () <Endl; // getdata () of the C class is called, which is not defined in C. Therefore, it is called in B, but not defined in B, therefore, getdata () in Class A is called. Because dogetdata () in Class A is a virtual function, dogetdata () in Class B is called, and dogetdata () in Class B returns B :: m_data, so output 1 cout <C. a: getdata () <Endl; // because dogetdata () in Class A is a virtual function, and this interface is not redefined in Class C, therefore, dogetdata () in Class B is called, while dogetdata () in Class B returns B: m_data, so 1 cout is output <C. b: getdata () <Endl; // certainly 1 cout is returned <C. c: getdata () <Endl; // because getdata () is not redefined in Class C, the getdata () inherited from Class B is called, but the Class B is not defined, therefore, getdata () in a is called. Because dogetdata () in a is a virtual function, dogetdata () in Class B is called, and dogetdata () in Class B returns B: m_data, therefore, output 1 cout <C. dogetdata () <Endl; // certainly the return value of Class B 1 is cout <C. a: dogetdata () <Endl; // because the dogetdata () of A is directly called, The cout output is 0 <C. b: dogetdata () <Endl; // because dogetdata () of B is directly called, cout is output. <C. c: dogetdata () <Endl; // because this interface is not redefined in Class C, dogetdata () in Class B is called, and dogetdata () in Class B returns B:: m_data, so the output is 1 system ("pause"); Return 0 ;}
Http://www.programfan.com/CLUB/showpost.asp? Id = 21686