从c ++中的两个类继承并插入到列表中

时间:2012-12-05 18:22:57

标签: c++

以下代码是否有关于从列表中插入从两个类继承的对象的问题?

class A
{
}

class B
{
}

class C : public A, public B
{

}

C *myObj = new C();
std::list<A*> myList;
myList.push_front(myObj);

是否正在创建类型A的列表并插入类型为C的对象,这是B类的一部分有问题? 我知道这段代码编译但我对内存问题很感兴趣。 如果它有问题,我还有什么其他选择来解决这个问题?

2 个答案:

答案 0 :(得分:3)

只要列表按引用或指针存储数据并且析构函数是虚拟的,你就可以了。

基本问题是您不允许将C存储到A变量中,但您可以将其存储到A&A*中。因此,A a = C()与将{C}存储到list<A>vector<A>一样糟糕。这将导致slicing

答案 1 :(得分:0)

从技术上讲,只要您将对象的引用或指针添加到列表中以避免切片并拥有虚拟析构函数,您就应该是安全的。

您可以将AB视为多态类型的接口。看一下这个例子:

class Drawable
{
    public:
        virtual ~Drawable() { }
        virtual void draw();
};

class Circle : public Drawable
{
    public:
        void draw() { std::cout << "Drawing a circle\n"; }
}

class Square : public Drawable
{
    public:
        void draw() { std::cout << "Drawing a square\n"; }
}

int main()
{
    std::list<Drawable*> shapeList { new Square(), new Circle(), new Square() };
}