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

前端 未结 4 1645
醉梦人生
醉梦人生 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:58

    Below is the expansion of solution suggested by anton.

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    class BaseClass
    {
        string s;
    
    public: 
        BaseClass() { s = "BaseClass";} 
    virtual ~ BaseClass(){}
    virtual void print()=0;
    };
    
    
    class Derived1 : public BaseClass
    {
        int i;
    public:
        Derived1() { i = 10; }
        void print() 
        {
            cout << i << std::endl;
        }
    
    };
    
    class Derived2 : public Derived1
    {
        float f;
    public:
        Derived2() { f = 4.3;}
        void print() 
        {
            cout << f << std::endl;
        }
    };
    
    class factory
    {
    mapm;
    BaseClass* obj;
    public:
    factory()
    {
    obj=NULL;
    }
    BaseClass* FindType(string s);
    void AddType(string s,BaseClass *obj);
    void deleter();
    ~factory(){cout<<"deleting objects from map"<second;
       }
    
       m.clear( );  
    
     }
    BaseClass* factory::FindType(string s)
    {
    if(m.find(s)!=m.end())
    {
    
    return  m[s];
    }
    
    return NULL;
    }
    
    int main()
    {   
       BaseClass* obj;
       factory fact_obj; 
       fact_obj.AddType("d1",new Derived1());
       fact_obj.AddType("d2",new Derived2());
       obj=fact_obj.FindType("d1");
       if(obj!=NULL)
          {
        obj->print();
          }
        obj=fact_obj.FindType("d2");
        if(obj!=NULL)
         {
         obj->print(); 
         }
    
        return 0;
    }
    

提交回复
热议问题