在国外一个网站中,其中一道题目自己理解不太明白,所以,在此,自己用程序实现一下,以便更好的理解。参考部分代码如下:
....... ....... class A { private: int i; public: virtual void vfoo(){ cout<<"Base"<<endl; } A():i(0){ cout<<"i:"<<i<<endl; cout<<"initial A()"<<endl; } ~A(){ cout<<"Delete A()"<<endl; } }; class B:public A{ private: int j; public: void vfoo(){ j++; cout<<"j:"<<j<<endl; cout<<"Derived"<<endl; } B():j(0){ cout<<"j:"<<j<<endl; cout<<"Initial B()"<<endl; } ~B(){ cout<<"Delete B()"<<endl; } }; class C:public B{ private: int k; public: C():k(0){ cout<<"k:"<<k<<endl; cout<<"Initial C()"<<endl; } ~C(){ cout<<"Delete C()"<<endl; } }; ....... ....... class AA{ ........ }; .......
测试主程序:
int main(){ A *p, oa; C oc; p = &oa; p->vfoo(); p =&oc; p->vfoo(); return 0; }输出结果:
i:0 initial A() i:0 initial A() j:0 Initial B() k:0 Initial C() Base j:1 Derived Delete C() Delete B() Delete A() Delete A()