在c ++中将派生类对象添加到基类对象的向量中?

时间:2013-04-03 00:14:33

标签: c++ class inheritance polymorphism

我很久没有使用过这个c ++功能了,所以忘了它。假设我有一个名为“object”的类,以及一个类“button”,它是从“object”公开派生的。

现在,考虑我有一个矢量a或hash_map a。我是否能够添加“button:in?”类型的对象?或者实际上是从“object”公开派生的任何其他类对象。我该怎么做?

由于

1 个答案:

答案 0 :(得分:1)

使用指针向量:

struct Base
{
    virtual ~Base() {}
    virtual int foo() = 0;   // good manners: non-leaf classes are abstract
};

struct Derived1 : Base { /* ... */ };
struct Derived2 : Base { /* ... */ };
struct Derived3 : Base { /* ... */ };

#include <vector>
#include <memory>

int main()
{
    std::vector<std::unique_ptr<Base>> v;

    v.emplace_back(new Derived3);
    v.emplace_back(new Derived1);
    v.emplace_back(new Derived2);

    return v[0]->foo() + v[1]->foo() + v[2]->foo();  // all highly leak-free
}
相关问题