[英]Proper Design to Avoid Use of Dynamic_Cast
我遇到的问题与此处提出的问题非常相似: 使用基类中没有的派生方法
在该问题中,IdeaHat提供的最高答案是使用dynamic_cast,但是他/她接着说,如果必须诉诸于此,那么您的设计就很糟糕。 我在其他问题中注意到非常相似的答案。
那么,在这种情况下正确的设计是什么?
为了便于讨论,我们使用以下代码:
enum AnimalType {
dog = 0,
cat
}
Class Animal {
virtual AnimalType getType() = 0;
void eat() {
cout << "Ate some food!" << endl;
}
void sleep() {
cout << "Zzzz..." << endl;
}
};
Class Dog : public Animal {
AnimalType getType() {
return AnimalType::dog;
}
void fetch() {
cout << "Fetched the stick!" << endl;
}
};
Class Cat : public Animal {
AnimalType getType() {
return AnimalType::cat;
}
};
//A factory function
Animal* shelter(AnimalType type) {
if(type == AnimalType::dog) {
return new Dog;
}
else {
return new Cat;
}
int main() {
Animal* pet = shelter(AnimalType::dog);
pet->fetch();
}
本质上,我有一家工厂生产特定类的多个子类。 一些子类包含父/其他子类中不存在的函数,这会在没有解决方法的情况下阻止使用多态。
我将如何以一种可行的方式实现这一目标,并且也将其视为“好的设计”?
简单:
void functionTakingAnimal(Animal& a) {
a.eat();
a.sleep();
}
int main() {
Dog pet;
pet.fetch();
functionTakingAnimal(pet);
}
不要在需要之前破坏静态类型信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.