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

前端 未结 3 1076
-上瘾入骨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 <iostream>
    
    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; 
    } 
    
    0 讨论(0)
  • 2021-01-20 17:12

    You're looking for a variant type. There's an upcoming std::variant in C++17, and C++11-compliant versions in boost and around the web. Example with boost::variant:

    struct visitor
    {
        void operator()(const A&){ cout << "HELLO A" << endl; }
        void operator()(const B&){ cout << "HELLO B" << endl; }
        void operator()(const C&){ cout << "HELLO C" << endl; }
    };
    
    int main()
    {
        visitor v;
    
        // `obj` is either an `A`, a `B` or a `C` at any given moment.
        boost::variant<A, B, C> obj{B{}};
        //                         ^^^^^
        //                   Initialize with `B`.
    
        boost::apply_visitor(v, obj); // prints "HELLO B"
    
        obj = A{};
        boost::apply_visitor(v, obj); // prints "HELLO A"
    }
    
    0 讨论(0)
  • 2021-01-20 17:16

    you could do something like

    if (key == "a") obj=new A();
    else if (key == "b")  obj=new B();
    
    0 讨论(0)
提交回复
热议问题