C++ storing an abstract object in an array

2019-09-19 15:14发布

问题:

I have been trying to pass object of an abstract class as by reference but it clearly gives error when I try to store this objects in an array of pointers with the same data type. Can anyone please explain what I'm doing wrong? It's in the following function:

    void enterItem(DessertItem& item) 
    {
        if (top != (maxSize-1))
        {
            arr[top] = &item;
            top++;
        }
    }

The dessertItem class is actually an abstract class and "arr" is a pointer array of dessertItem so it can give reference to any new object whenever it gets passed by reference. I can't get it how am I supposed to do that? Here's the class:

    class Checkout

    {

        ////Maintains a list of DessertItem references.
        protected:

        int maxSize;

        int top;

        DessertItem **arr;


    public:

    Checkout()

     {

    ///Creates a Checkout instance with an empty list of DessertItem's 


         this->maxSize=5;
         this->top=0;
         this->arr = new DessertItem*[maxSize];
         for(int i=0; i<maxSize; i++)
         {
             arr[i]=NULL;
         }
     }


     ////Clears the Checkout to begin checking out a new set of items 
    void clear()

    {

        for(int i=0; i<maxSize; i++)
         {
             arr[i]=NULL;
         }
    }


    //A DessertItem is added to the end of the list of items

    void enterItem(DessertItem &item) 

    {

        if(top!=(maxSize-1))


        {
            arr[top]=&item;
            top++;
        }
    }


     //Returns the number of DessertItem's in the list 


    int numberOfItems()

    {

        return this->top;
    }

    };

回答1:

store your abstract objects in a vector<unique_ptr<T>>. when you construct them, construct them as unique_ptr, eg:

class Base {
public:
  virtual ~Base() = default;
  virtual void method() = 0;
};

class Impl : public Base {
public:
    void method() override { /* perform action here */ };
};

create and store like so:

// nasty old c-style array
std::unique_ptr<Base> a[10];
a[0] = std::move(std::unique_ptr<Base>(new Impl));

// std::vector 
std::unique_ptr<Base> p { new Impl };
std::vector<std::unique_ptr<Base>> v;

v.push_back(std::move(p));
// or
v.emplace_back(new Impl);


标签: c++ oop