简体   繁体   English

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

[英]adding derived class objects to a vector of bas class objects in c++?

I have not used this c++ feature since a long time, so have just forgotten about it. 我已经很长时间没有使用过此c ++功能了,所以就忘了它。 Suppose I have a class called "object", and a class "button", which is publicly derived from "object". 假设我有一个名为“ object”的类和一个“ button”类,它是从“ object”公开派生的。

Now, consider i have a vector a, or a hash_map a. 现在,考虑我有一个向量a或hash_map a。 Will I be able to add objects of type "button: in it? or in fact any other class objects publicly derived from "object". How can I do this? 我可以在其中添加“按钮:”类型的对象吗?或者实际上可以从“对象”公开派生任何其他类对象。我该怎么做?

Thanks 谢谢

Use a vector of pointers: 使用指针向量:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM