1.第一段代码

#include<iostream>
 using namespace std;
 class ClxBase{
 public:
     ClxBase() {};
       void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
 }; class ClxDerived : public ClxBase{
 public:
     ClxDerived() {};
       void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
 };
   int   main(){  
   ClxDerived *p =  new ClxDerived;
   p->DoSomething();
   delete p;
   return 0;


 

运行结果:

           

Output from the destructor of class ClxDerived!

 

   这段代码中基类的析构函数不是虚函数,在main函数中用继承类的指针去操作继承类的成员,释放指针P的过程是:先释放继承类的资源,再释放基类资源. 


2.第二段代码

#include<iostream>
 using namespace std;
 class ClxBase{
 public:
     ClxBase() {};
       void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
 }; class ClxDerived : public ClxBase{
 public:
     ClxDerived() {};
       void DoSomething() { cout << "Do something in class ClxDerived!" << endl; }
 };
   int   main(){  
   ClxBase *p =  new ClxDerived;
   p->DoSomething();
   delete p;
   return 0;
   }

输出结果:

Do something in class ClxBase!
Output from the destructor of class ClxBase!

  

  

  

   析构函数自然也应该如此:如果它想析构子类中的重新定义或新的成员及对象,当然也应该声明为虚的. 


3.第三段代码:

#include<iostream>
 using namespace std;
 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() {};
     ~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };
     void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
 }; int   main(){  
   ClxBase *p =  new ClxDerived;
   p->DoSomething();
   delete p;
   return 0;
   }

运行结果:

Do something in class ClxDerived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!

   这段代码中基类的析构函数被定义为虚函数,在main函数中用基类的指针去操作继承类的成员,释放指针P的过程是:只是释放了继承类的资源,再调用基类的析构函数.调用dosomething()函数执行的也是继承类定义的函数.