猿问

解释一下最终的输出答案

#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();

}


一变骷髅
浏览 1484回答 1
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()函数。
随时随地看视频慕课网APP
我要回答