Can you create a std::map of inherited classes?

前端 未结 4 1644
醉梦人生
醉梦人生 2021-01-14 12:14

I\'m wondering if it\'s possible to create a map of pointers of inherited classes. Here\'s an example of what I\'m trying to do:

#include 
#inc         


        
4条回答
  •  一生所求
    2021-01-14 12:48

    First things first:

    template
    map m;
    

    This is not valid C++ and could only mean something like a template alias, but I believe, that is not what you are looking for.

    Storing polymorphic objects in C++ is complicated by slicing (constructing a value of the base type from a value of a derived type). Dynamic polymorphism can only be handled through references or pointers. You could potentially use std::ref or boost::ref for situations in which the map will only be passed down the callstack, but this requires some care. Often, storing pointers to the base is the way to go: std::map. Managing deallocation yourself is rather tedious and either std::map or std::map are preferred, depending if you need shared semantics or not.

    Basic example. Someone should replace this with something more meaningful.

    #include 
    #include 
    #include 
    #include 
    
    class animal
    {
    public:
      virtual ~animal() {};
      virtual void make_sound() const = 0;
    };
    
    class dog : public animal
    {
    public:
      void make_sound() const { std::cout << "bark" << std::endl; }
    };
    class bird : public animal
    {
    public:
      void make_sound() const { std::cout << "chirp" << std::endl; }
    };
    
    int main()
    {
      std::map> m;
      m.insert(std::make_pair("stupid_dog_name", new dog));
      m.insert(std::make_pair("stupid_bird_name", new bird));
      m["stupid_dog_name"]->make_sound();
      return 0;
    }
    

提交回复
热议问题