課程
/后端開(kāi)發(fā)
/C++
/C++遠(yuǎn)征之多態(tài)篇
為什么形參Flyable* f1可以調(diào)用plane的指針, 是應(yīng)為plane是Flyable的子類么??
2015-10-23
源自:C++遠(yuǎn)征之多態(tài)篇 3-6
正在回答
/** 這就是所謂的多態(tài)啊 */ 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
舉報(bào)
本教程將帶領(lǐng)大家體會(huì)面向?qū)ο笕筇匦灾械亩鄳B(tài)特性
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號(hào)-11 京公網(wǎng)安備11010802030151號(hào)
購(gòu)課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號(hào)
2015-11-11