Array of base abstract class containing children class in C++

本小妞迷上赌 提交于 2019-12-02 16:07:58

问题


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.



来源:https://stackoverflow.com/questions/12942979/array-of-base-abstract-class-containing-children-class-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!