#include <iostream>
using namespace std;
class People
{
protected:
char name[32];
public:
People(char *n)
{
strcpy(name, n);
}
virtual void show()
{
cout << "name=" << name << endl;
}
};
class Student : public People //多态成立条件一:要有继承
{
protected:
int age;
public:
Student(char *n, int a): People(n)
{
age = a;
}
void show() //多态成立条件二:虚函数重写 派生类的virtual可省略 因为派生类具有覆盖关系,与基类同名函数将自动成为虚函数
{
cout << "name=" << name << " " << "age=" << age << endl;
}
};
int main()
{
Student s("aaa",1);
s.show(); //默认调用派生类成员
s.People::show();
cout << "===================" << endl;
People *p = new People("bbb"); //基类指针指向基类对象
p->show();
Student *ps = new Student("bbb",2); //派生类指针指向派生类对象
ps->show();
p = new Student("bbb",2); //多态成立条件三:基类指针指向派生类对象 调用派生类函数
p->show();
delete p;
delete ps;
cout << "===============" << endl;
People *pc = NULL;
pc = new People("ccc");
pc->show();
pc = new Student("ccc",3);
pc->show();
delete pc;
return 0;
}
总结:多态成立条件
1、要有继承关系
2、派生类中要有虚函数重写
3、基类指针指向派生类对象