[問題] virtual & copy contructor

看板C_and_CPP (C/C++)作者 (winest)時間15年前 (2010/10/08 10:08), 編輯推噓3(308)
留言11則, 5人參與, 最新討論串1/1
請問一下版上大大們 假設我現在有兩個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
你把void test( Base b )改成void test( Base* b )
10/08 10:13, 1F

10/08 10:14, , 2F
polymorphism要在pointer或reference才有效
10/08 10:14, 2F

10/08 10:23, , 3F
可是這樣compiler是怎麼處理的,我知道如果用pointer的方式
10/08 10:23, 3F

10/08 10:23, , 4F
去指的話的確是b->vTable->say()會印出Derive這是正常的,
10/08 10:23, 4F

10/08 10:24, , 5F
但現在用call by value的方式,應該是整個Derive物件傳過去
10/08 10:24, 5F

10/08 10:24, , 6F
,說錯,複製一份過去,然後再依Base的copy contructor去把
10/08 10:24, 6F

10/08 10:25, , 7F
複製的那份的vTable給b.vTable,所以應該還是Derive才對吧
10/08 10:25, 7F

10/08 11:34, , 8F
vtable 不會像一般成員那樣被複製
10/08 11:34, 8F

10/08 11:35, , 9F
不然你用Base去呼叫Derive::say的話
10/08 11:35, 9F

10/08 11:35, , 10F
又要如何去存取 Derive 的成員?
10/08 11:35, 10F

10/08 13:06, , 11F
靜態型別 vs 動態型別
10/08 13:06, 11F
文章代碼(AID): #1ChdqesP (C_and_CPP)
文章代碼(AID): #1ChdqesP (C_and_CPP)