首页 > 解决方案 > Vector in an abstract class

问题描述

I believe that the question here is similar however I still need more clarification on it.

Let's say I create a vector inside an abstract class (which stores objects of another class). How would I be able to use .pushback() from another class if I can't initialise an object of an abstract class?

Obviously the easiest solution is to put the vector in another class but I need another way. I've read you can do this by storing pointers to those objects in a vector. But can somebody give me an example please?

标签: c++vector

解决方案


The purpose of an abstract class is to provide an interface that is then implemented in concrete derived classes.

If you want to push items onto the vector which is a data member of the abstract class, then create an appropriate derived class and then you can create an instance of that derived class, which will thus contain a vector you can add entries to.

class Base{
public:
  virtual void do_stuff()=0; // this is an abstract base class
protected:
  std::vector<int> data;
};

class Derived: public Base
{
public:
  void do_stuff() {
    // concrete implementation
    data.push_back(42); // can add values to vector inherited from base class
  }
};

int main()
{
  Derived d;
  d.do_stuff(); // will add entries to d.data
}

However, I wonder if that is really what you are trying to achieve.


推荐阅读