为了账号安全,请及时绑定邮箱和手机立即绑定

void flyMatch(Flyable* f1, Flyable * f2)

为什么形参Flyable* f1可以调用plane的指针, 是应为plane是Flyable的子类么??

正在回答

1 回答

/**
这就是所谓的多态啊
*/

class Father{
public:
    virtual void func(){std::cout<<"father"<<std::endl;}
};

class Child:public Father{
public:
    // override Father's function func()
    void func(){std::cout<<"child"<<std::endl;}
};

// usage
Father *f = new Father();
f->func(); // output "father"
Child c = new Child();
c->func(); // output "child"

Father *pf = NULL;
Father *pc = NULL;

pf = c; // pointer of Father type points to object of Child which is Father's subclass
pf->func(); // output "child", because the real type of the object is Child. (polymorphic)

//pc = f; // this is WRONG!! child pointer can not points to father object
pc = dynamic_cast<Child*>(pf); // right


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
C++远征之多态篇
  • 参与学习       66209    人
  • 解答问题       334    个

本教程将带领大家体会面向对象三大特性中的多态特性

进入课程

void flyMatch(Flyable* f1, Flyable * f2)

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号