Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

oop - C++ storing an abstract object in an array

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

    };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...