创建一个变量来保存不同类型的对象C ++ [英] Create a variable to hold objects of different types C++

查看:147
本文介绍了创建一个变量来保存不同类型的对象C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个不同的对象 A B C 。根据给定的参数,我想在这些不同的对象之间进行选择。在编程中,

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 programming,

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; 
} 

我考虑过模板和结构对象。但是到目前为止,它们都不起作用。

I have thought about templates and struct objects. But none of them work so far.

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; 
} 

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

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

编辑。
我不能更改 A B C 。我得到了可以使用的这些类,我的目标是实现 main 方法。因此,继承对我来说是不可能的。抱歉给您带来任何混乱。

Edit. I can't change class A, B and C. I was given these classes to work with and my goal is to implement main method. So, inheritance was out of the question for me. Sorry for any confusion.

感谢您的帮助。

推荐答案

您正在寻找变体类型。 C ++ 17中即将发布 std :: variant boost 符合C ++ 11的版本在网络上。 boost :: variant的示例

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"
}

这篇关于创建一个变量来保存不同类型的对象C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆