【发布时间】:2021-08-09 22:18:21
【问题描述】:
考虑以下示例:
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void makeSound() {cout << "rawr" << endl;}
};
class Dog : public Animal
{
public:
virtual void makeSound() {cout << "bark" << endl;}
};
int main()
{
Animal animal;
animal.makeSound();
Dog dog;
dog.makeSound();
Animal badDog = Dog();
badDog.makeSound();
Animal* goodDog = new Dog();
goodDog->makeSound();
}
输出是:
rawr
bark
rawr
bark
但我认为输出肯定应该是“rawr bark bark bark”。坏狗怎么了?
更新:你可能对another question of mine感兴趣。
【问题讨论】:
-
我认为你的变量有一些命名错误。
-
代码甚至无法按原样编译。还有
void main()???呃…… -
我不明白为什么有人会否决这个问题——这既不是“不清楚”也不是“没用”。 +1 否决反对票。
-
指南“使非叶类抽象”可以防止这种意外。
-
另一个 +1 用于发布一个完整的、最小的示例来说明问题。这正是我们一直要求的。
标签: c++ polymorphism