[問題] 轉型的問題

看板C_and_CPP (C/C++)作者 (幸福!)時間16年前 (2010/04/28 13:53), 編輯推噓1(106)
留言7則, 4人參與, 最新討論串1/2 (看更多)
程式碼如下,我想問的是,為什麼Test2結果會是CDerived呢?因為const? 還是?謝謝~:D class CBase { public: virtual void Test() const { cout << "Output from CBase!" << endl; }; }; class CDerived : public CBase { public: virtual void Test() const { cout << "Output from CDerived!" << endl; }; }; void Test1(CBase test) { test.Test(); } void Test2(const CBase& test) { test.Test(); } CDerived oTest; Test1(oTest); Test2(oTest); -- 查你IP (づ′▽`)づ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.64.227.34

04/28 14:23, , 1F
因為Test()是宣告成virtual
04/28 14:23, 1F

04/28 14:31, , 2F
如果是這樣的話..那Test1會何是CBase呢?
04/28 14:31, 2F

04/28 15:06, , 3F
因為傳進去的oTest被轉成CBase型態的test
04/28 15:06, 3F

04/28 15:10, , 4F
那const CBase& test 傳進去的呢?@@
04/28 15:10, 4F

04/28 15:41, , 5F
by value 會發生切割,by ref 不會。
04/28 15:41, 5F

04/28 16:05, , 6F
應該說 by value 會產生一個 CBase 的暫時物件?
04/28 16:05, 6F

04/28 16:11, , 7F
喔喔....切割的問題!!!thx..
04/28 16:11, 7F
文章代碼(AID): #1BryriKX (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1BryriKX (C_and_CPP)