Pointer to array of base class, populate with derived class

前端 未结 5 376
心在旅途
心在旅途 2020-12-15 09:47

If I have a base class, with only virtual methods and 2 derived classes from the base class, with those virtual methods implemented.

How do I:

 // ca         


        
5条回答
  •  心在旅途
    2020-12-15 10:12

    It is C++ use std::vector instead of simple array:

    std::vector base;
    base.push_back(new FirstDerivedClass());
    base.push_back(new SecondDerivedClass());
    

    As Kerrek SB noticed safest method is to use std::unique_ptr:

    std::vector > base;
    base.push_back( std_unique_ptr(new FirstDerivedClass()) );
    base.push_back( std_unique_ptr(new SecondDerivedClass()) );
    

提交回复
热议问题