// AnotherDemo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream.h"
class ClxBase
{
public:
ClxBase() {}
virtual ~ClxBase() { cout << "Output from the destructor of class ClxBase!" << endl; }
virtual void DoSomething() { cout << "Do something in class ClxBase!" << endl; }
};
class ClxDerived : public ClxBase
{
public:
ClxDerived() {};
virtual ~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; }
//此处的virtual可以去掉
virtual void DoSomething() { cout << "Do something in class ClxDerived!" << endl; }
//此处的virtual可以去掉
};
class ClxThrived : public ClxDerived
{
public:
ClxThrived(){}
virtual ~ClxThrived(){cout << "Output from the destructor of class ClxThrived!" << endl;}
//此处的virtual可以去掉
virtual void DoSomething(){cout << "Do something in class ClxThrived!" << endl;}
//此处的virtual可以去掉
};
void main()
{
cout << "ClxBase *pTest1 = new ClxBase" << endl;
ClxBase *pTest1 = new ClxBase;
pTest1->DoSomething();
delete pTest1;//1
cout << "ClxBase *pTest2 = new ClxDerived" << endl;
ClxBase *pTest2 = new ClxDerived;
pTest2->DoSomething();
delete pTest2;//2 用基类的指针删除一个派生类的对象时
cout << "ClxDerived *pTest3 = new ClxDerived" << endl;
ClxDerived *pTest3 = new ClxDerived;
pTest3->DoSomething();
delete pTest3;//3
cout << "ClxBase *pTest4 = new ClxThrived" << endl;
ClxBase *pTest4 = new ClxThrived;
pTest4->DoSomething();
delete pTest4;//4 用基类的指针删除一个派生类的对象时
cout << "ClxDerived *pTest5 = new ClxThrived" << endl;
ClxDerived *pTest5 = new ClxThrived;
pTest5->DoSomething();
delete pTest5;//5 用基类的指针删除一个派生类的对象时
cout << "ClxThrived *pTest6 = new ClxThrived" << endl;
ClxThrived *pTest6 = new ClxThrived;
pTest6->DoSomething();
delete pTest6;//6
}
/*
ClxBase *pTest1 = new ClxBase
Do something in class ClxBase!
Output from the destructor of class ClxBase!
ClxBase *pTest2 = new ClxDerived
Do something in class ClxDerived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!
ClxDerived *pTest3 = new ClxDerived
Do something in class ClxDerived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!
ClxBase *pTest4 = new ClxThrived
Do something in class ClxThrived!
Output from the destructor of class ClxThrived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!
ClxDerived *pTest5 = new ClxThrived
Do something in class ClxThrived!
Output from the destructor of class ClxThrived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!
ClxThrived *pTest6 = new ClxThrived
Do something in class ClxThrived!
Output from the destructor of class ClxThrived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!
Press any key to continue
*/
virtual ~ClxDerived()
最新推荐文章于 2019-11-19 17:40:35 发布