#include <iostream>
using namespace std;
class Animal {
public:
virtual void cry(){
cout << "Animal Cry" << endl;
}
void name(){
cout << "Animal Name " << endl;
}
};
class Dog : public Animal {
public:
virtual void cry(){
cout << "Dog Cry" << endl;
}
void name(){
cout << "Dog Name " << endl;
}
};
int main(){
Animal *animal1 = new Dog();
animal1->cry(); //Dog::cry();
Dog *dog1 = new Dog();
dog1->cry(); //Dog::cry();
animal1->name(); // Animal::name();
dog1->name(); // Dog::name();
return 1;
}
Dog Cry
Dog Cry
Animal Name
Dog Name
从上面可以看出,没有加virtual 的函数,不是调用子类覆盖的方法
而加了virtual 的函数,都是调用子类覆盖的方法(Dog::cry())