考虑以下示例:
#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
但是我认为输出肯定应该是“ raw kark bark bark”。badDog怎么了?
更新:您可能对我的另一个问题感兴趣。
一只斗牛犬
慕田峪4524236
相关分类