Create a variable to hold objects of different types C++

前端 未结 3 1077
-上瘾入骨i
-上瘾入骨i 2021-01-20 16:47

I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In

3条回答
  •  不知归路
    2021-01-20 17:04

    It seems to me that you should use a virtual common base class/struct and a pointer to this base class/struct.

    The following is a full working example

    #include 
    
    struct Base
     { virtual void printHello () = 0; };
    
    class A : public Base { 
      public: 
        void printHello() { std::cout << "HELLO A" << std::endl; }
    }; 
    
    class B  : public Base{ 
      public: 
        void printHello() { std::cout << "HELLO B" << std::endl; }  
    };
    
    class C  : public Base{ 
       public: 
         void printHello() { std::cout << "HELLO C" << std::endl; }  
    }; 
    
    int main () { 
        std::string key = "c"; 
        A a; 
        B b; 
        C c; 
        Base * obj; 
    
        if (key == "a") obj = &a; 
        else if (key == "b") obj = &b; 
        else obj = &c;
        obj->printHello(); // print Hello C.
        return 0; 
    } 
    

提交回复
热议问题