Container that stores a mixture of base and derived objects?

前端 未结 4 1748
说谎
说谎 2021-01-07 03:51

What is the right thing to do? I know that if the container is of base class value type, then derived object stored is \'sliced\'. If container is of derived class type, the

4条回答
  •  花落未央
    2021-01-07 04:31

    There is example with std::vector and std::shared_ptr. I think that's what you want.

    #include 
    #include 
    #include 
    
    class Base {
    public:
       virtual void foo() {
          std::cout << "base" << std::endl;
       }
    };
    
    class Derived : public Base {
       void foo() {
          std::cout << "derived" << std::endl;
       }
    };
    
    int main()
    {
       std::vector > v;
       v.push_back(std::shared_ptr(new Base));
       v.push_back(std::shared_ptr(new Derived));
    
       for (auto it : v) {
          it->foo();
       }
    }
    

提交回复
热议问题