Array of base abstract class containing children c

2019-03-03 14:35发布

问题:

so I have a Top class, let say:

//Top.h
#pragma once
#include <string>
using std::string;

class Top
{
    protected:
        string name;
    public:
        virtual string GetName() = 0;
}

This class won't have any object Top instantiate, that's why it's an abstract class. I also have two Middle class, let say:

//MiddleA.h
#pragma once
#include "Top.h"

class MiddleA : public Top
{
    protected:
        int value;
    public:
        MiddleA(string, int);
        string GetName();
        int GetValue();
}

//MiddleB.h
class MiddleB : public Top
{
    protected:
        double factorial;
    public:
        MiddleB(string, double);
        string GetName();
        double GetFactorial();
        double Calculate(int);
}

Now, what I need is an array, or anything, that can contains multiple objects of type MiddleA, MiddleB or any classes that inherit from those two classes. Is there a way to do this in C++?

EDIT : Would it be "acceptable" to add a default constructor in the protected section and use a vector or array of Top?

回答1:

Use the pointers and arrays of C++:

typedef std::array<std::unique_ptr<Top>,3> Tops;
Tops tops =
{{
    new MiddleA( "Kuku", 1337 ),
    new MiddleB( "Hoi", 42.0 ),
    new MiddleC()
}};

Only thing you have to have virtual destructor on your Top. Without virtual destructor you may only use shared_ptr, others will result with undefined behavior when objects are destroyed.



回答2:

yes. You could do it this way.

Top* array[3] = { new Top(parms), new MiddleA(params), new MiddleB(params) };

but you will be only able to call GetName() function. You wouldnt be able to call other methods.