温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c++ - Base constructor calls derived constructor depending on input
c++ c++11 design-patterns factory oop

c++ - 基本构造函数根据输入调用派生构造函数

发布于 2020-04-14 11:01:09

假设我有一个人类班级:

class Human {
public:
    bool isFemale;
    double height;
    Human(bool isFemale, double height) {
        this->isFemale = isFemale;
        this->height = height;
    }
};

以及派生类(例如Female和Male),它们实现了自己的方法。在C ++ 11中,我是否有一种方法可以在运行时根据Human构造函数的输入来确定Human应该是哪种“子类型”(男性或女性)?对于男性和女性,我在各自的课堂上采用不同的行为方式。我要尝试做的是在运行时根据构造函数的输入确定Human是Female类型还是Male类型,因此我可以(之后)根据其类型应用适当的行为。理想的情况是始终调用Human构造函数,并在运行时选择适当的子类型,具体取决于一个在构造函数中输入的参数。如果可能的话,我想应该扭转“人类”构造函数,但是我不确定如何...

查看更多

提问者
GabCaz
被浏览
58
38.2k 2020-02-03 19:08

通过调用Human的构造函数,您只能创建一个Human对象。

据我了解,您想根据运行时获得的性别输入来创建一个MaleFemale对象。然后,您可能应该考虑使用工厂功能来实现此目的。

例如,如果您定义MaleFemale为:

struct Male: public Human {
   Male(double height): Human(false, height) {}
   // ...
};

struct Female: public Human {
   Female(double height): Human(true, height) {}
   // ...
};

然后,您可以使用以下工厂功能make_human()

std::unique_ptr<Human> make_human(bool isFemale, double height) { 
   if (isFemale)
      return std::make_unique<Female>(height);
   return std::make_unique<Male>(height);
}

它在运行时根据传递给参数的参数决定是创建一个对象Female还是Male对象isFemale

只需记住make Human的析构函数,virtual因为MaleFemale类都公开继承Human