2

我是 C++ 新手,我有一个问题。

假设我们有一个基类 Base 和两个派生类,Derived1 和 Derived2。fe Derived1 有一个采用整数的构造函数,而 Derived2 有一个采用布尔值的构造函数。

是否可以在运行时(或编译时)确定创建这两个子类中的哪一个并将其分配给基类。

像这样:Base b = ???(value),其中 value 的类型是整数或布尔值。

提前致谢!

4

3 回答 3

8

编写一个名为 的函数的两个重载createMyBlaBla。一个接受int,一个接受bool。每个人都返回所需的派生类类型。例如:

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

人们称之为工厂模式。

于 2010-01-24T01:18:14.843 回答
6

您可能需要Factory Design Pattern

于 2010-01-24T01:18:20.863 回答
0

我真的不认为这可能是你想要的方式,C++ 中的多态性不能像这样工作。

如果我理解得很好,你想要一个声明为 Base 的变量,取决于参数类型,它是 Derived1 还是 Derived2,所有这些都不使用工厂模式。

这不可能的原因是,Base 该类并不真正意识到其Derived 类的存在,也不能声明堆栈变量并使其“表现”为派生类。但是,我可以建议一种解决方法,但话又说回来,这并不能满足您想要的真实类层次结构的所有期望(如果您真的想要那样的话_:

class Facade{

public:
    Facade(int foo) : b(new Derived1(foo)){}

    Facade(bool foo) : b(new Derived2(foo)){}

    Base Value()
    {
        return *b;
    }

private:
    Base* b;

};

然后您可以执行以下操作:

Facade foo(10);
Facade bar(true);

int x = (reinterpret_cast<Derived1*>(foo.Value())) -> val;
bool y = (reinterpret_cast<Derived2*>(bar.Value())) -> val;
于 2010-01-24T03:44:41.323 回答