C++ How do I create a dynamic array of objects inherited from an abstract class?

后端 未结 3 1295
一生所求
一生所求 2020-12-22 02:58

My task specifically states that I have to create a random array of Squares and Triangles, that are inherited from an abstract class Figure, and then I have to print out the

3条回答
  •  臣服心动
    2020-12-22 03:47

    Figure *dyn_arr = new Figure[size]; // this doesn't work

    It doesn't work because we cannot create an array of Figures because of the pure virtual function. We wouldn't want to create a Figure by itself in any case. We only want to create either a Square or a Triangle and their sizes may differ. So there is no way to allocate the memory when the array is created.

    You could create an array of pointers (size is known at compile time) and then iterate over that:

    auto dyn_arr = new Figure*[size];
    // auto in the above context becomes Figure** (pointer to a pointer)
    for(int i = 0; i < size; i++) 
        cout << dyn_arr[i]->square();
    

    Please keep in mind that arrays and pointers used this way is prone to errors. Far better to use std::make_unique and std::vector.

    Here is one way to randomly create the objects:

    Figure* go_figure()
    {
        std::uniform_int_distribution ud{0,1};
        static std::random_device rd{};
        switch(ud(rd))
        {
            case 0: return new Square{};
            case 1: return new Triangle{};
        }
    }
    
    int main()
    {
        int size = 20;
        auto dyn_arr = new Figure*[size];
        for(int i = 0; i < size; i++)
            dyn_arr[i] = go_figure();
        for(int i = 0; i < size; i++) 
            cout << dyn_arr[i]->square();
        for(int i = 0; i < size; i++) 
            delete dyn_arr[i];
        delete[] dyn_arr;
    }
    

提交回复
热议问题