当用指向基类的指针变量指向子类的对象时,可以通过指针引用子类中定义的成员函数,从而实现运行时的多态性。
#include <iostream.h>
class A
{
public:
virtual void display()
{
cout<<"This is the Base class A"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout<<"This is the Derived class B"<<endl;
}
};
class C:public A
{
public:
void display()
{
cout<<"This is the Derived class C"<<endl;
}
};
void main()
{
A *ptr;
A x;
B y;
C z;
ptr=&x;
ptr->display();
ptr=&y;
ptr->display();
ptr=&z;
ptr->display();
}
运行结果:
This is the Base class A
This is the Derived class B
This is the Derived class C