#include<iostream>
#include<cstdio>
using namespace std;
class Base
{
public:
Base(){ cout << "Base()" << endl; }
virtual ~Base(){ cout << "~Base()" << endl; }
virtual void out()
{
cout << "Base::out()" << endl;
}
};
class Derived :public Base
{
public:
Derived(){ cout << "Derived()" << endl; }
~Derived(){ cout << "~Derived()" << endl; }
void out()
{
cout << "Derived::out()" << endl;
}
};
void main()
{
//Base b;
Derived d;
//Derived *pd=&b; //error,子类类型的指针不能指向父类对象的地址
Derived *pd = &d;
Base *pb = &d; //ok,父类类型的指针可以指向子类对象的地址
pd->out();
pb->out();
Base *pbb = new Derived();
pbb->out();
delete pbb;
}
运行期多态
最新推荐文章于 2021-09-12 14:50:30 发布