使用虚函数和多态来避免使用 dynamic_cast 的方法,以减少代码耦合。
示例代码如下:
#include
// 基类 Animal
class Animal {
public:
virtual void sound() const = 0;
};
// 派生类 Dog
class Dog : public Animal {
public:
void sound() const override {
std::cout << "Woof!" << std::endl;
}
};
// 派生类 Cat
class Cat : public Animal {
public:
void sound() const override {
std::cout << "Meow!" << std::endl;
}
};
// 使用虚函数和多态来避免使用 dynamic_cast
void printAnimalSound(const Animal& animal) {
animal.sound();
}
int main() {
Dog dog;
Cat cat;
// 直接传递派生类对象给函数,不需要进行 dynamic_cast
printAnimalSound(dog); // 输出: Woof!
printAnimalSound(cat); // 输出: Meow!
return 0;
}
在上面的示例代码中,我们定义了一个基类 Animal,并在派生类 Dog 和 Cat 中实现了 sound() 函数。然后,我们编写了一个名为 printAnimalSound() 的函数,它接受一个 Animal 对象的引用,并调用其 sound() 函数。
在 main() 函数中,我们创建了一个 Dog 对象和一个 Cat 对象,并分别将它们传递给 printAnimalSound() 函数。由于我们将对象作为 Animal 类型的引用传递,而不是使用 dynamic_cast 进行类型转换,因此避免了使用 dynamic_cast。