[英]c++: Dynamically choose which subclass to create
I am new to c++ and i have a question. 我是c ++的新手,我有一个问题。
Lets say we have a base class Base and two derived classes, Derived1 and Derived2. 假设我们有一个基类Base和两个派生类Derived1和Derived2。 fe Derived1 has a constructor taking a integer and Derived2 a constructor taking a boolean. fe Derived1有一个带整数的构造函数,Derived2有一个带布尔值的构造函数。
Is it possible to determine at run time (or at compile time) which of those two subclasses to create and assign it to the Base class. 是否有可能在运行时(或在编译时)确定要创建这两个子类中的哪一个并将其分配给Base类。
Something like this: Base b = ???(value), where value is of type integer or boolean. 像这样:Base b = ???(value),其中value是integer或boolean类型。
Thanks in advance! 提前致谢!
Write two overloads of a function called createMyBlaBla
. 写一个名为createMyBlaBla
的函数的两个重载。 One accepting int
, and the other accepting bool
. 一个接受int
,另一个接受bool
。 Everyone returns the desired derived class type. 每个人都返回所需的派生类类型。 eg: 例如:
Base* create(int n)
{
return new Derived1(n);
}
Base* create(bool b)
{
return new Derived2(b);
}
....
Base* b1 = create(10); // Derived1
Base* b2 = create(false); // Derived2
People call this the factory pattern. 人们称之为工厂模式。
您可能想要工厂设计模式 。
I don't really think this is possible the way you want it to be, polymorphism in C++ just doesn't work like this. 我真的不认为这可能是你想要它的方式,C ++中的多态性就是这样。
If I understood well, you want a variable declared as Base decides, depending on the parameter type, whether it is going to be Derived1 or Derived2, all without using the Factory pattern. 如果我理解得很好,你想要一个声明为Base的变量决定,取决于参数类型,它是否将是Derived1或Derived2,所有这些都不使用Factory模式。
The reason why this is not possible is that, the Base
class is not really aware of the existence of its Derived
classes nor you can declare a stack variable and make it "behave" as a derived class. 这是不可能的原因是, Base
类并不真正意识到它的Derived
类的存在,也不能声明一个堆栈变量并使其“行为”作为派生类。 However, I can suggest a work-around but then again, this doesn't satisfy all the expectations of the real class hierarchy you want (if you really want it that way_: 但是,我可以建议一个解决方法,但是再次,这不能满足你想要的真正的类层次结构的所有期望(如果你真的想要它那样:
class Facade{
public:
Facade(int foo) : b(new Derived1(foo)){}
Facade(bool foo) : b(new Derived2(foo)){}
Base Value()
{
return *b;
}
private:
Base* b;
};
And then you can do something like: 然后你可以这样做:
Facade foo(10);
Facade bar(true);
int x = (reinterpret_cast<Derived1*>(foo.Value())) -> val;
bool y = (reinterpret_cast<Derived2*>(bar.Value())) -> val;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.