代码:
#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(); // rawr (1)
Dog dog;
dog.makeSound(); // bark (2)
Animal badDog = Dog();
badDog.makeSound(); // (3) rawr !!!!!!!!!!!!!!!!!!!
Animal* goodDog = new Dog();
goodDog->makeSound(); // bark (4)
}
定义了一个Animal
类,派生类Dog
,如果不使用指针或引用,badDog
的类型永远是Animal
类型,而不会是别的类型。Animal badDog = Dog()
将一个新的Dog
对象复制到badDog
, 由于badDog
只是Animal
类型,只会将Dog
对象进行切片,取属于Animal
的部分,称为切片(slicing)。
[1] https://stackoverflow.com/questions/4403726/learning-c-polymorphism-and-slicing