我有 3 个不同的对象A
, B
and 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;
in JAVA
因为Java中的每个对象都是Object
班级。但是我如何在 C++ 中实现这一点呢?
编辑。
我无法转班级A
, B
and C
。我被安排了这些课程,我的目标是实施main
方法。所以,inheritance
对我来说这是不可能的。抱歉造成任何混乱。
任何帮助表示赞赏。
您正在寻找一个variant
类型。有一个即将到来的std::variant
在 C++17 和 C++11 兼容版本中boost
和网络周围。示例为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"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)