本文主要是介绍析构函数(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
析构函数什么情况下要定义为虚函数?
1.第一段代码
#include<iostream>
using namespace std;
class ClxBase{
public:ClxBase() {};~ClxBase() {cout << "Output from the destructor of class ClxBase!" << endl;};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(){ ClxDerived *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!
2.第二段代码
#include<iostream>
using namespace std;
class ClxBase{
public:ClxBase() {};~ClxBase() {cout << "Output from the destructor of class ClxBase!" << endl;};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 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!
这篇关于析构函数(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!