2013-03-10 28 views
1

這只是爲了學習的目的,因爲我似乎是無法找到這樣的答案任何別的地方.. 所以我有多個問題..我不會做這樣的事情,但我只是想知道,因爲我的大腦需要我知道,否則我會在一天的其餘時間感到不舒服。多態性陣列弄清楚哪些兒童是

假設我有以下類別:

class Control 
{ 
    //virtual stuff.. 
}; 

class Button : public Control 
{ 
    //More virtual stuff.. 
}; 

class CheckBox : public Control 
{ 
    //More virtual stuff.. 
}; 

因此按鈕和CheckBox是相同的母控制的姐妹。

現在假設有人好奇像MOI看到這樣的事情:

std::vector<Control> ListOfControls; //Polymorphic Array. 
ListOfControls.push_back(Button());  //Add Button to the Array. 
ListOfControls.push_back(CheckBox()); //Add CheckBox to the Array. 

我如何才能知道什麼數據類型數組持有?我怎麼知道ListOfControls [0]包含一個Button並且ListOfControls [1]包含一個CheckBox? 我讀了你最有可能做一個動態轉換,如果沒有返回null,它是一個特定的數據類型:

if (dynamic_cast<Button*>(ListOfControls[0]) == ???) //I got lost.. :(

另一件事要下車,我的腦海:

假設相同的類以上,你怎麼說的:

std::vector<void*> ListOfControls;   //Polymorphic Array through Pointer. 
ListOfControls.push_back(new Button());  //Add Button to the Array. 
ListOfControls.push_back(new CheckBox()); //Add CheckBox to the Array. 

有沒有辦法做到既上面的例子中沒有動態轉換或有某種伎倆來解決它?我讀了動態轉換通常是從來沒有想過..

最後,你能不能向下轉換從家長到孩子?

Button Btn; 
Control Cn; 

Btn = (Button) Cn; //??? 

回答

3

由於slicing,您不能擁有多態對象的容器;你需要有一個指向多態對象的指針的容器。儘管如此,你是對的。你不得不使用dynamic_casttypeid得到數組包含指向對象的運行時類型。

但是,你應該嘗試編寫不依賴於實際類型多態對象的代碼;你應該推廣基類中的接口,並在指針上調用這些成員函數。這使你的代碼更清潔,更具有可擴展現有的代碼稍加修改。

+0

:秒,但我編譯上面並沒有抱怨。什麼是切?任何鏈接? TypeID似乎說他們都是「7Control」 – Brandon 2013-03-10 22:51:49

+0

@CantChooseUsernames是的,一個非常好的鏈接:http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c – 2013-03-10 22:52:18

+1

@CantChooseUsernames: http://en.wikipedia.org/wiki/Object_slicing。 – 2013-03-10 22:52:23