【问题标题】:adding derived class objects to a vector of bas class objects in c++?将派生类对象添加到 C++ 中的 bas 类对象向量中?
【发布时间】:2013-04-03 00:14:33
【问题描述】:

好久没用过这个c++特性了,暂时忘记了。假设我有一个名为“object”的类和一个从“object”公开派生的类“button”。

现在,假设我有一个向量 a,或者一个 hash_map a。我能否在其中添加“按钮:”类型的对象?或者实际上是从“对象”公开派生的任何其他类对象。我该怎么做?

谢谢

【问题讨论】:

    标签: c++ class inheritance polymorphism


    【解决方案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
    }
    

    【讨论】:

    • 这里emplace_backpush_back 有什么优势吗?
    • @MattPhillips: emplacement 用于显式转换,这里需要。一个半更好的解决方案将涉及make_unique,不幸的是它不存在。
    • 对于从Derived*std::unique_ptr&lt;Base&gt; 的显式转换?您能否解释一下 T&amp;&amp;T&amp; 有何不同,或提供链接?
    猜你喜欢
    • 2013-08-11
    • 2013-02-05
    • 2014-04-24
    • 2018-09-17
    • 2020-10-15
    • 2021-11-26
    • 2014-02-02
    • 2021-12-19
    • 2014-09-07
    相关资源
    最近更新 更多