#include <iostream.h>class A{public:A(){ cout<<"A constructor called!"<<endl; }void f(){ cout<<"f() is called in A!"<<endl; }};class B :public A{public:B(){ cout<<"B constructor called!"<<endl; } virtual void f(){ cout<<"f() is called in B!"<<endl; }};class C:public B{public: C(){cout<<"C constructor called!"<<endl;}void f(){cout<<"f() is called in C!"<<endl;} };void main(){ A * pa; B * pb; pa = pb = new C; pa->f(); pb->f();}
1 回答
絮絮念秋风
TA贡献4条经验 获得超1个赞
pa->f()输出f() is called in A!
pb->f()输出f() is called in C!
这里是C++多态的例子。多态就是对于有虚函数的父类对象来说(这里是B* pb),对象实际指向的类型不由声明决定,而是由赋值决定的,所以pb = new C以后,实际pb指向的是C类型,所以调用pb->f()的时候,实际调用的是C的f()函数。而A没有虚函数(或纯虚函数),所以pa = new C并不会触发pa的多态,也就是pa还是A类型,所以调用pa->f()的时候,实际调用的是A的f()函数。
- 1 回答
- 0 关注
- 1483 浏览
添加回答
举报
0/150
提交
取消