简体   繁体   English

我如何将多个类存储在一个变量中,也许是一个列表? 或矢量? 多态性

[英]How would I store multiple classes within a variable, maybe a list? or vector? Polymorphism

I'm still somewhat new to c++ and I'm unsure about creating different instances within a list.我对 C++ 还是有点陌生​​,我不确定是否在列表中创建不同的实例。 In my program I have multiple classes inheriting from the base class:在我的程序中,我有多个从基类继承的类:

class Foo{

}

class Bar : public Foo {

}

class Fin : public Foo {

}

The problem that I am facing is I need to replace one with another in case one is destroyed.我面临的问题是我需要用另一个替换一个以防万一。 For example:例如:

for (int i = 0; i < list/vector/? ; i++){
    if (bar_i[i].destroyed()){
        Fin fin_i = new Fin(); // in place of Bar
    }
}

which would then take the Bar(s) spot.然后将占据 Bar(s) 位置。 What could I use to create a list, vector, or whatever to create the instances of multiple classes?我可以用什么来创建列表、向量或其他任何东西来创建多个类的实例?

You can't store different types in the standard containers (a standard container requires all elements to be of the same type).您不能在标准容器中存储不同类型(标准容器要求所有元素都属于同一类型)。

However, you can use polymorphism and store pointers to a parent (common) type.但是,您可以使用多态并存储指向父(公共)类型的指针。

You may want to rethink your design and move common methods and members to a parent type.您可能需要重新考虑您的设计并将常用方法和成员移至父类型。

Edit 1: Example implementation编辑 1:示例实现

std::vector<Foo *> container;
for (unsigned int i = 0; i < 6; ++i)
{
  if (i & 1)
  {
    container.push_back(new Bar);
  }
  else
  {
    container.push_back(new Fin);
  }
}
  for (unsigned int i = 0; i < 6; ++i)
  {
    container[i]->Common_Operation();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM