我正在尝试实现多态,即根据传递给函数的实例来调用派生类的特定方法。
我不确定这是否可能。任何指导都是非常有用的。
代码如下:
#include <iostream>
using namespace std;
class Animal
{
public:
void speak()
{
cout << "Base: Animal Speaking!" << endl;
}
};
class Dog : public Animal
{
public:
void speak()
{
cout << "Dog: Woof!" << endl;
}
};
class Cat : public Animal
{
public:
void speak()
{
cout << "Cat: Meow!" << endl;
}
};
class FarmAnimal : public Animal
{
public:
void speak(Animal *animal)
{
animal->speak();
}
};
int main()
{
Dog dog = Dog();
Cat cat = Cat();
FarmAnimal farm_animal = FarmAnimal();
dog.speak();
cat.speak();
farm_animal.speak(&dog);
farm_animal.speak(&cat);
return 0;
}输出:
Dog: Woof!
Base: Meow!
Base: Animal Speaking!
Base: Animal Speaking!预期输出:
Dog: Woof!
Base: Meow!
Dog: Woof!
Cat: Meow!发布于 2020-12-29 12:12:12
你当然可以。
我建议让Animal成为一个“抽象”基类。将函数声明为virtual,并通过将它们设置为0来使它们“纯”(强制派生类覆盖它们才能被实例化)。
class Animal
{
public:
virtual ~Animal() = default; // allows polymorphic destruction too
virtual void speak() = 0;
};然后将您的派生类标记为覆盖基类:
class Dog : public Animal
{
public:
void speak() override
{
cout << "Dog: Woof!" << endl;
}
};
class Cat : public Animal
{
public:
void speak() override
{
cout << "Cat: Meow!" << endl;
}
};至于FarmAnimal,我不会为继承而疯狂。这个类看起来像一个奇怪的模型,因为它在其他动物上操作,而不是它自己。过度继承会导致复杂的设计。
https://stackoverflow.com/questions/65487162
复制相似问题