[英]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.