[問題] 子類別覆寫父類別成員變數

看板C_and_CPP作者 (kj)時間11年前 (2014/09/25 11:05), 編輯推噓0(0010)
留言10則, 3人參與, 最新討論串1/1
如題 假使父類別有個member variable,在父類別的function中被使用 我繼承了一個子類別,想要用一個新的東西去替代父類別中的member variable 不知道是否有辦法做到呢 程式碼如下: tool_base是在原先base中被使用的class 我繼承了這兩個class,想改寫一部份的行為 (derived & tool_derived) 不知道是否有辦法直接覆寫掉呢? class tool_base { public: tool_base() { } ~tool_base() { } void show_name() { printf("my name is tool_base\n"); } }; class tool_derived : public tool_base { public: tool_derived() { } ~tool_derived() { } virtual void show_name() { printf("my name is tool_derived\n"); } }; class base { public: base() { } ~base() { } void show_tool_name() { tool.show_name(); } tool_base tool; }; class derived : public base { public: derived() { } ~derived() { } tool_derived tool; }; derived d; d.show_tool_name(); <--- 其實我這邊預期的是希望會呼叫tool_derived.show_name() 這樣子的想法不知道是否有辦法達成呢,謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.120.66.84 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1411614303.A.FCF.html

09/25 11:24, , 1F
可達成, virtual function 用法錯了
09/25 11:24, 1F

09/25 11:43, , 2F
請問一下那邊弄錯了呢?
09/25 11:43, 2F

09/25 11:48, , 3F
tool_base跟tool_derived的tool是不同的namespace
09/25 11:48, 3F

09/25 11:49, , 4F
如果繼承下來的話d會有兩塊記憶體都叫tool(內容不同)
09/25 11:49, 4F

09/25 11:50, , 5F
如果是呼叫base class的show_tool_name
09/25 11:50, 5F

09/25 11:50, , 6F
會直接對應到base class的tool_base tool;
09/25 11:50, 6F

09/25 11:51, , 7F
想知道是否有不override show_tool_name的方式
09/25 11:51, 7F

09/25 16:20, , 8F
你不想 override 任何東西? 那 d 當成 base 後的 tool 要是?
09/25 16:20, 8F

09/25 16:42, , 9F
哪些部分能動, 如果都不能動就無解
09/25 16:42, 9F

09/25 16:43, , 10F
只要 class base 裡面的 tool 能改成 pointer, 就簡單了
09/25 16:43, 10F
文章代碼(AID): #1K8uPV_F (C_and_CPP)