简体   繁体   中英

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. 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. 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

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();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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