包含 C++ 子类的基本抽象类数组 [英] Array of base abstract class containing children class in C++

查看:29
本文介绍了包含 C++ 子类的基本抽象类数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个顶级课程,比如说:

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

这个类不会有任何对象Top实例化,这就是为什么它是一个抽象类.我也有两个中产阶级,比如说:

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

现在,我需要的是一个数组或任何东西,它可以包含类型为 MiddleA、MiddleB 的多个对象或从这两个类继承的任何类.有没有办法在 C++ 中做到这一点?

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++?

在受保护的部分添加一个默认构造函数并使用一个向量或Top数组是否可以接受"?

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

推荐答案

使用 C++ 的指针和数组:

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

唯一必须在顶部具有虚拟析构函数的东西.如果没有虚拟析构函数,您只能使用 shared_ptr,其他人会在销毁对象时导致未定义的行为.

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.

这篇关于包含 C++ 子类的基本抽象类数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆