多态最常用的例子
// 父类
class animal
{
public:
virtual void eat()
{
cout << "animal eat" << endl;
}
virtual void sleep()
{
cout << "animal sleep" << endl;
}
};
// 子类
class person :public animal
{
public:
void eat()
{
cout << "person eat" << endl;
}
void sleep()
{
cout << "person sleep" << endl;
}
};
// 子类
class dog :public animal
{
public:
void eat()
{
cout << "dog eat" << endl;
}
void sleep()
{
cout << "dog sleep" << endl;
}
};
void xxx_fun(animal* ptr)
{
ptr->eat();
ptr->sleep();
}
void test()
{
animal a;
person p;
dog d;
xxx_fun(&a);
xxx_fun(&p);
xxx_fun(&d);
}