多态数组计算出哪些孩子在其中

时间:2013-03-10 22:49:41

标签: c++ polymorphism

这只是为了学习目的,因为我似乎无法在其他任何地方找到这样的答案。 所以我有多个问题......我不会做这样的事情,但我只是想知道,因为我的大脑需要我知道,否则我会在一天剩下的时间里感到不舒服。

假设我有以下课程:

class Control
{
    //virtual stuff..
};

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

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

因此,Button和CheckBox是同一位母亲Control的姐妹。

现在假设像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.

如何判断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; //???

1 个答案:

答案 0 :(得分:3)

由于slicing,您不能拥有多态对象的容器;你需要一个容器来指向多态对象的某种指针。不过你是对的;你必须使用dynamic_casttypeid来获取数组包含指针的对象的运行时类型。

但是,您应该尝试编写不依赖于多态对象的实际类型的代码;你应该在基类中概括接口,只需在指针上调用那些成员函数。这使得您的代码很多更清晰,更易于扩展,只需对现有代码进行最少的修改。