C++实例之虚函数(析构函数和普通函数)

来源:互联网 发布:如何安装cad软件 编辑:程序博客网 时间:2024/06/05 17:44
#include "stdafx.h"#include <iostream>using namespace std;/* 情形一// 输出为:// Output from the constructor of class ClxBase!// Output from the constructor of class ClxDerived!// Do something in class ClxDerived!// Output from the destructor of class ClxDerived!// Output from the destructor of class ClxBase!*/class ClxBase{//本例父类中析构函数是否为virtual对输出结果没有影响public:    ClxBase() { cout << "Output from the constructor of class ClxBase!" << endl; };    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() { cout << "Output from the constructor of class ClxDerived!" << endl; };    ~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };     void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };};int _tmain(int argc, _TCHAR* argv[]){ClxDerived *pTest = new ClxDerived;pTest->DoSomething();delete pTest;return 0;}/* 情形二// 输出为:// Output from the constructor of class ClxBase!// Output from the constructor of class ClxDerived!// Do something in class ClxDerived!// Output from the destructor of class ClxDerived!// Output from the destructor of class ClxBase!*/class ClxBase{//本例父类中析构函数是否为virtual对输出结果没有影响public:    ClxBase() { cout << "Output from the constructor of class ClxBase!" << endl; };    virtual ~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() { cout << "Output from the constructor of class ClxDerived!" << endl; };    ~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };     void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };};int _tmain(int argc, _TCHAR* argv[]){ClxDerived *pTest = new ClxDerived;pTest->DoSomething();delete pTest;return 0;}/* 情形三// 输出为:// Output from the constructor of class ClxBase!// Output from the constructor of class ClxDerived!// Do something in class ClxBase!// Output from the destructor of class ClxDerived!// Output from the destructor of class ClxBase!*/class ClxBase{//本例父类中析构函数和DoSomething()函数是否为virtual对输出结果没有影响public:    ClxBase() { cout << "Output from the constructor of class ClxBase!" << endl; };    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() { cout << "Output from the constructor of class ClxDerived!" << endl; };    ~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; }; };int _tmain(int argc, _TCHAR* argv[]){ClxDerived *pTest = new ClxDerived;pTest->DoSomething();delete pTest;return 0;}


 

原创粉丝点击