将抽象派生类对象存储在基类向量中

时间:2018-04-07 13:48:38

标签: c++ vector polymorphism abstract-class

通过存储基类指针,我学会了将派生类指针存储在基类向量中:

vector<base*> base_vector;
base_vector.push_back(new derived());
// free memory at the end

但如果我有一个抽象的基类:

class interface {
public:
    virtual interface(){} 
    virtual ~interface(){}
};

从中派生出两个更抽象的类。

class abstract_derived_1 : virtual public interface 
{ 
public:
    virtual abstract_derived_1(){} 
    virtual ~abstract_derived_1(){}
};

class abstract_derived_2 : virtual public interface 
{ 
public:
    virtual abstract_derived_2(){} 
    virtual ~abstract_derived_2(){}
};

来自辅助抽象类的其他几个派生类:

class derived_1 : virtual public interface, virtual public abstract_derived_1
{
private:
    double value;
public:
    derived_1(){value=0;}
    derived_1(const double val1, const double val2) { value = val1+val2; }
    ~derived_1(){}
};


class derived_2 : virtual public interface, virtual public abstract_derived_2
{
private:
    string name;
public:
    derived_2(){name="";}
    derived_2(string my_str) { name = my_str; }
};

是否可以将所有这些存储在多态矢量中?像往常一样,我做了以下事情:

vector<abstract_derived_1*> abs1;
vector<abstract_derived_2*> abs2;
abs1.push_back(new derived_1(1,2));
abs2.push_back(new derived_2("polymorphism"));

但是如何将两个多态向量存储在基类向量中?

vector</* What should I put in here? */> interface_vector;

2 个答案:

答案 0 :(得分:1)

derived_1derived_2的新实例推送到通用向量vector<interface*>没有问题,因为它们具有interface类作为祖先。

顺便说一下:您不需要derived_1班级和derived_2班级再次从interface继承。这是不常见的,我很确定这可能会导致其他问题。

答案 1 :(得分:0)

vector<interface*> interface_vector;
// Loop through abs1 with an index of i
interface_vector.push_back(dynamic_cast<interface*>(abs1[i]));
// Loop through abs2 with an index of i
interface_vector.push_back(dynamic_cast<interface*>(abs2[i]));

只需添加上面的循环即可。重点是,您可以投放到interface*,这是vector<interface*>所期望的。