[問題] virtual & copy contructor
請問一下版上大大們
假設我現在有兩個class
class Base
{
public :
virtual void say() { cout << "Base" << endl; }
};
class Derive : public Base
{
public :
virtual void say() { cout << "Derive" << endl; }
};
原則上,Base和Derive會各自有一個vTable,其中的vTable->say再指向各
自的say() method,所以可以想成
struct Base
{
Base_vTable * vTable;
}
Base::Base
{
this.vTable->say = Base::say;
}
struct Derive
{
Base_vTable * vTable;
}
Derive
{
Base::Base();
this.vTable->say = Derive::say;
}
這樣才能達到polymorphism,用Base class去呼叫Derive class的實作
問題來了,當我測試下面這行程式碼時
void test( Base b )
{
b.say();
}
int main( int argc , char ** argv )
{
Base * ptr = (Base *)new Derive();
test( *ptr );
}
為什麼是跑出Base???
理論上copy constructor應該會直接b.vTable = (*ptr).vTable才對
所以這時候的b.say()會變成使用Derive的vTable而印出Derive
還是說compiler會對參數的型態做檢查然後改指針位置嗎??
謝謝各位耐心看完
--
復向東,見一商港,然商販皆金髮碧眼,料是海外來朝之英吉利商販集散所在,
舶來異寶眾多,正目眩神迷間,琴聲價響,佇聽之,或如山壑雅秀,或如水潭靜謐,
時悠遠輕揚,復而厚實凝重,令人神馳,急尋琴聲來處,見一英吉利女子正自奏藝販琴,
當下文思泉湧,兼有結識之意,於是突出人群,吟詩唱和:"商娥扶碧曲,秀謐悠而厚..."
詩未竟,曲驟斷,但見英女神色驚訝,連聲曰諾,正暗喜間,卻見數名英商巡官怒目而來
倒拖吾身,飽以老拳。嗟乎,奈何蠻夷終究不識詩詞曲賦之美...。 《文學之美》
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.115.53.26
→
10/08 10:13, , 1F
10/08 10:13, 1F
推
10/08 10:14, , 2F
10/08 10:14, 2F
→
10/08 10:23, , 3F
10/08 10:23, 3F
→
10/08 10:23, , 4F
10/08 10:23, 4F
→
10/08 10:24, , 5F
10/08 10:24, 5F
→
10/08 10:24, , 6F
10/08 10:24, 6F
→
10/08 10:25, , 7F
10/08 10:25, 7F
推
10/08 11:34, , 8F
10/08 11:34, 8F
→
10/08 11:35, , 9F
10/08 11:35, 9F
→
10/08 11:35, , 10F
10/08 11:35, 10F
推
10/08 13:06, , 11F
10/08 13:06, 11F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章