作者liptonbin (我還存在耶)
看板C_and_CPP
標題[問題] 請問繼承/virtual function的列印順序
時間Wed Mar 11 22:58:23 2015
請教一下
class Base{
public:
virtual void func{cout<<"Base"<<endl;}
};
class Derived1:public Base{
public:
void func(){cout<<"Derived1"<<endl;}
};
class Derived2:public Derived1{
public:
void func(){cout<<"Derived2"<<endl;}
};
int main(){
Derived2 *ptr_b=new Derived2;
ptr_b->func();
Derived2 *ptr_a=dynamic_case<Derived1 *>(ptr_b);
ptr_a->func();
Base *ptr_bs=dynamic_case<Base *>(ptr_b);
ptr_bs->func();
delete ptr_b;
}
請問為什麼會列印?
ans:
Derived2
Derived2
Derived2
謝謝
--
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.249.172.69
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1426085906.A.8D4.html
→ Jockey66666: 因為 Derived2 *ptr_b=new Derived2; 03/11 23:28
→ liptonbin: 我是想問後面那兩個 第一個印法我知道 03/11 23:46
→ littleshan: 因為 ptr_a 和 ptr_bs 實際上都指向 Derived2 object 03/12 00:40
→ littleshan: 如果這不在你的預期之內,表示你對virtual的理解有誤 03/12 00:41
→ littleshan: 然後,問問題時至少先讓你的程式能compile吧... 03/12 00:42
→ carylorrk: 先不說這個,你聽過多型嗎? 03/12 01:29
推 kwpn: dynamic_case是哪一種case? 03/12 13:06
→ Jockey66666: 你打錯字那個就不說了, 因為你new Derived2 03/12 21:45
→ Jockey66666: 所以才是Derived2阿.. 03/12 21:46