[英]Proper Design to Avoid Use of Dynamic_Cast
I'm experiencing an issue very similar to the question asked here: Using derived methods that aren't in the base class 我遇到的问题与此处提出的问题非常相似: 使用基类中没有的派生方法
In that question, the top answer, provided by IdeaHat, is to use dynamic_cast, but then he/she goes on to say that if you have to resort to that, then your design is bad. 在该问题中,IdeaHat提供的最高答案是使用dynamic_cast,但是他/她接着说,如果必须诉诸于此,那么您的设计就很糟糕。 I've noticed very similar answer in other questions.
我在其他问题中注意到非常相似的答案。
So, then, what is the proper design in such a situation? 那么,在这种情况下正确的设计是什么?
For the sake of discussion, let's use this code: 为了便于讨论,我们使用以下代码:
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();
}
Essentially, I have a factory producing multiple subclasses of a particular class. 本质上,我有一家工厂生产特定类的多个子类。 Some of the subclasses contain functions not present in the parent/other subclasses, which would prevent the use of polymorphism without a workaround.
一些子类包含父/其他子类中不存在的函数,这会在没有解决方法的情况下阻止使用多态。
How would I implement this in a fashion that works and would also be considered "good design"? 我将如何以一种可行的方式实现这一目标,并且也将其视为“好的设计”?
Easy: 简单:
void functionTakingAnimal(Animal& a) {
a.eat();
a.sleep();
}
int main() {
Dog pet;
pet.fetch();
functionTakingAnimal(pet);
}
Don't destroy static type information earlier than you need to. 不要在需要之前破坏静态类型信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.