Gab*_*Caz 1 c++ oop design-patterns factory c++11
Let's say I have a Human class:
class Human {
public:
bool isFemale;
double height;
Human(bool isFemale, double height) {
this->isFemale = isFemale;
this->height = height;
}
};
Run Code Online (Sandbox Code Playgroud)
and derived classes, such as Female and Male, which implement their own methods. Do I have a way, in C++11, to determine at runtime, depending on the inputs into the Human constructor, which "sub-type" (Male or Female) Human should be? I am putting different behaviour for Male and Female in their respective classes. What I am trying to do is determine at runtime whether Human is of type Female or of type Male, depending on constructor input, so I can (afterwards) apply appropriate behaviour based on its type. The ideal would be to always call the Human constructor, and the appropriate sub-type to be chosen at runtime, depending on the parameters one enters in the constructor. If that is possible, I guess one should twist the "Human" constructor, but I'm unsure how...
通过调用Human的构造函数,您只能创建一个Human对象。
据我了解,您希望根据在运行时获得的性别输入创建一个Male或Female对象。然后,您可能应该考虑使用工厂函数来实现这一点。
例如,如果您将Male和定义Female为:
struct Male: public Human {
Male(double height): Human(false, height) {}
// ...
};
struct Female: public Human {
Female(double height): Human(true, height) {}
// ...
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下工厂函数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);
}
Run Code Online (Sandbox Code Playgroud)
它在运行时根据传递给参数的参数决定是创建一个对象Female还是一个Male对象isFemale。
请记住 makeHuman的析构函数,virtual因为Male和Female类都公开继承自Human.