// 封装:
// 隐藏实现
// 也就是看不到这些功能是如何实现的
class Animal {
public:
virtual void eat(char* food) = 0;
virtual void sleep() = 0;
};
// 继承:
class Dog : public Animal {
public:
virtual void eat(char* food) {
cout << "dog eat " << food << endl;
}
virtual void sleep() {
cout << "dog sleep" << endl;
}
void bark() {
cout << "dog bark" << endl;
}
};
// 继承
class Fish : public Animal {
public:
virtual void eat(char* food) {
cout << "fish eat " << food << endl;
}
virtual void sleep() {
cout << "fish sleep" << endl;
}
void swim() {
cout << "fish swim" << endl;
}
}
// 多态:
// 表面上 dog 的类型变成了 Animal
void foo() {
Dog dog = new Dog();
Animal animal = dog;
dog.eat("bone"); // 正确
dog.bark(); // 正确
animal.eat("bone"); // 正确
animal.bark(); // 编译错误
((Dog)animal).bark(); // 正确
((Fish)animal).sleep(); // 编译通过,运行错误
((Fish)animal).swim(); // 编译通过,运行错误
}