課程
/后端開發
/C++
/C++遠征之多態篇
為什么形參Flyable* f1可以調用plane的指針, 是應為plane是Flyable的子類么??
2015-10-23
源自:C++遠征之多態篇 3-6
正在回答
/** 這就是所謂的多態啊 */ 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
舉報
本教程將帶領大家體會面向對象三大特性中的多態特性
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2015-11-11