加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

创建一个变量来保存不同类型的对象C.

发布时间:2020-12-16 10:05:58 所属栏目:百科 来源:网络整理
导读:我有3个不同的对象A,B和C.根据给定的参数,我想在这些不同的对象中进行选择.在编程中, class A { public: void printHello() { cout "HELLO A" endl; }}; class B { public: void printHello() { cout "HELLO B" endl; } };class C { public: void printHello
我有3个不同的对象A,B和C.根据给定的参数,我想在这些不同的对象中进行选择.在编程中,

class A { 
  public: 
    void printHello() { cout << "HELLO A" << endl; }
}; 

class B { 
  public: 
    void printHello() { cout << "HELLO B" << endl; }  
};

class C { 
   public: 
     void printHello() { cout << "HELLO C" << endl; }  
}; 

int main () { 
    string key = "c"; 
    A a; 
    B b; 
    C c; 
    Object obj; // I don't know how to declare Object. 

    if (key == "a") obj = a; 
    else if (key == "b") obj = b; 
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0; 
}

我考虑过模板和结构对象.但到目前为止他们都没有工作.

template<typename T1,T2,T3> 
T1 getType(string key,T1 t1,T2 t2,T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1; 
    else if (key == "b") return t2; 
    else return t3; 
}

创建Object o很容易;在JAVA中,因为Java中的每个对象都是Object类的子类.但是我如何在C中实现这一目标?

编辑.
我不能改变A,B和C类.我得到了这些课程,我的目标是实现main方法.所以,继承对我来说是不可能的.对不起任何困惑.

任何帮助表示赞赏.

解决方法

您正在寻找变体类型.在C 17中有一个即将推出的std :: variant,以及在boost和Web上的C 11兼容版本. 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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读