我試圖了解動態型別轉換。如何使用 dynamic_cast 正確實作 DrawAnimals 和 Talk To Animals 功能?
DrawAnimals 繪制可以繪制的動物。這樣的動物實作了 Drawable 介面。TalkToAnimals 與會說話的動物進行對話,即它們實作了 Speakable 介面。
class Speakable {
public:
virtual ~Speakable() = default;
virtual void Speak(ostream& out) const = 0;
};
class Drawable {
public:
virtual ~Drawable() = default;
virtual void Draw(ostream& out) const = 0;
};
class Animal {
public:
virtual ~Animal() = default;
void Eat(string_view food) {
cout << GetType() << " is eating "sv << food << endl;
energy_;
}
virtual string GetType() const = 0;
private:
int energy_ = 100;
};
class Bug : public Animal, public Drawable {
public:
string GetType() const override {
return "bug"s;
}
void Draw(ostream& out) const override {
out << "(-0_0-)"sv << endl;
}
};
class Cat : public Animal, public Speakable, public Drawable {
public:
void Speak(ostream& out) const override {
out << "Meow-meow"sv << endl;
}
void Draw(ostream& out) const override {
out << "(^w^)"sv << endl;
}
string GetType() const override {
return "cat"s;
}
};
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
/*if (const Animal* r = dynamic_cast<const Animal*>(&animals)) {
} else if (const Bug* c = dynamic_cast<const Bug*>(&animals)) {
}*/
}
void TalkToAnimals(const std::vector<const Animal*> animals, ostream& out) {
//?
}
void PlayWithAnimals(const std::vector<const Animal*> animals, ostream& out) {
TalkToAnimals(animals, out);
DrawAnimals(animals, out);
}
int main() {
Cat cat;
Bug bug;
vector<const Animal*> animals{&cat, &bug};
PlayWithAnimals(animals, cerr);
}
uj5u.com熱心網友回復:
我將解釋為DrawAnimals,您可以自行擴展到其他功能。
你在這里做了什么:
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
/*if (const Animal* r = dynamic_cast<const Animal*>(&animals)) {
} else if (const Bug* c = dynamic_cast<const Bug*>(&animals)) {
}*/
}
完全錯誤有幾個原因:
animals是一個向量- 如果您打算使用單個元素,那么因為
&animals[i](i = [0..animals.size()])是指向指標 (Animal**)的指標 - 因為
dynamic_cast<const Animal*>(animals[i])(i = [0..animals.size()])是身份。
您需要使用向量的每個單獨元素:
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
for (auto animal : animals) {
if (const Drawable* r = dynamic_cast<const Drawable*>(animal)) {
// this animal is Drawable
} else if (const Bug* c = dynamic_cast<const Bug*>(animal)) {
// this animal is a Bug
// only issue here: Bugs are also Drawable
// so this code will never be reached
}
}
}
問題:為什么有的動物有Drawable,有的沒有?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475361.html
上一篇:C 使用動態記憶體創建佇列
