[問題] 有關多型的問題
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
g++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
標頭擋有
問題(Question):
想在 vector 或 set 容器放入不同型別的物件
餵入的資料(Input):
none
預期的正確結果(Expected Output):
Base Call!!
Derived Call!!
錯誤結果(Wrong Output):
Base Call!!
Base Call!!
程式碼(Code):(請善用置底文網頁, 記得排版)
#include<iostream>
#include<vector>
using namespace std;
class Base{
public:
virtual void call() const {
cout << "Base Call!!" << endl;
}
};
class Derived : public Base{
public:
virtual void call() const {
cout << "Derived Call!" << endl;
}
};
int main(){
vector<Base> v_base;
v_base.push_back( Base() );
v_base.push_back( Derived() );
v_base[0].call();
v_base[1].call();
return 0;
}
補充說明(Supplement):
我明明 push derived class 輸出卻不是 "Derived Call!!"
如果我想要輸出 "Derived Call!" 怎麼辦?? 存指標?? ( vector<Base*> )
那如果 Base class overload operator< 且容器是 set 呢?? set存指標就沒有意義了...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 182.235.35.88
→
06/29 13:37, , 1F
06/29 13:37, 1F
不好意思,請問 instance 是??
→
06/29 13:38, , 2F
06/29 13:38, 2F
vector< Base& >???
推
06/29 13:38, , 3F
06/29 13:38, 3F
→
06/29 13:39, , 4F
06/29 13:39, 4F
因為我不可能拿指標去搜尋,我都有他的指標了我就可以直接用他啦
→
06/29 13:40, , 5F
06/29 13:40, 5F
推
06/29 13:40, , 6F
06/29 13:40, 6F
※ 編輯: WJAider 來自: 182.235.35.88 (06/29 13:43)
→
06/29 13:41, , 7F
06/29 13:41, 7F
→
06/29 13:41, , 8F
06/29 13:41, 8F
喔喔!!!我都忘了這件事
→
06/29 13:41, , 9F
06/29 13:41, 9F
→
06/29 13:42, , 10F
06/29 13:42, 10F
不好意思,剛剛講法有誤,如果我現在有兩個內容一樣的 Base 但是記憶體位置不同
我把第一個 Base 放入 set 容器
用第二個搜尋卻沒有結果,這樣很奇怪
所以我覺得沒有意義
不過剛剛 littleshan大大 點醒我了,其實這樣做是可以的
謝謝大家
※ 編輯: WJAider 來自: 182.235.35.88 (06/29 13:49)
推
06/29 13:46, , 11F
06/29 13:46, 11F
對不起剛剛頭腦打結了...
→
06/29 13:47, , 12F
06/29 13:47, 12F
我想自己寫一個處理檔案的程式
類別有以下:
class File_System_Node{};
class Flle_System_Dir : public File_System_Node {};
class File_System_File : public File_System_Node {};
class Flie_System{
private:
set<Flie_System_Node> s_fsn;
};
大概是這樣
※ 編輯: WJAider 來自: 182.235.35.88 (06/29 13:54)
推
06/29 13:58, , 13F
06/29 13:58, 13F
→
06/29 13:59, , 14F
06/29 13:59, 14F
→
06/29 14:00, , 15F
06/29 14:00, 15F
恩恩我再改寫成指標的方式,受教了
File_System 還沒有寫完,不過大概就是 copy, move, search 等等的檔案操作
還有把樹狀圖印出來的 print 之類的功能
※ 編輯: WJAider 來自: 182.235.35.88 (06/29 14:05)