本文介绍了包含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()
}};

只有你必须在你的Top上有虚拟析构函数。没有虚拟析构函数你只能使用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 ++中的子类的基本抽象类的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:19