std::map unable to handle polymorphism?

前端 未结 5 595
时光说笑
时光说笑 2021-01-18 23:38

When using std::map in c++, is it possible to store inherited classes as their \"base class\" in the map and still being able to call their overloaded methods? See this exam

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 00:18

    First idea is that to get polymorphism you need to call member method on pointer or reference. I would store pointer to base class in the map (the element that you store gets copied) and then call via pointer like this:

    #include 
    #include 
    
    class Base
    {
        public:
        virtual void Foo() { std::cout << "1"; }
    };
    
    class Child : public Base
    {
        public:
        void Foo() { std::cout << "2"; }
    };
    
    int main (int argc, char * const argv[])
    {
        std::map Storage;
        Storage["rawr"] = new Child();
        Storage["rawr"]->Foo();
        return 0;
    }
    

    You get result "2".

    Note: You have to take care of the allocated memory now.

提交回复
热议问题