#includeMFC.cppclass CObject { public: CObject() { std::cout << "CObject Constructor" << std::endl; } ~CObject() { std::cout << "CObject Destructor" << std::endl; } }; class CCmdTarget : public CObject { public: CCmdTarget() { std::cout << "CCmdTarget Constructor" << std::endl; } ~CCmdTarget() { std::cout << "CCmdTarget Destructor" << std::endl; } }; class CWinThread : public CCmdTarget { public: CWinThread() { std::cout << "CWinThread Constructor" << std::endl; } ~CWinThread() { std::cout << "CWinThread Destructor" << std::endl; } }; class CWinApp : public CWinThread { public: CWinApp* m_pCurrentWinApp; public: CWinApp() { m_pCurrentWinApp = this; std::cout << "CWinApp Constructor" << std::endl; } ~CWinApp() { std::cout << "CWinApp Destructor" << std::endl; } }; class CDocument : public CCmdTarget { public: CDocument() { std::cout << "CDocument Constructor" << std::endl; } ~CDocument() { std::cout << "CDocument Destructor" << std::endl; } }; class CWnd : public CCmdTarget { public: CWnd() { std::cout << "CWnd Constructor" << std::endl; } ~CWnd() { std::cout << "CWnd Destructor" << std::endl; } }; class CFrameWnd : public CWnd { public: CFrameWnd() { std::cout << "CFrameWnd Constructor" << std::endl; } ~CFrameWnd() { std::cout << "CFrameWnd Destructor" << std::endl; } }; class CView : public CWnd { public: CView() { std::cout << "CView Constructor" << std::endl; } ~CView() { std::cout << "CView Destructor" << std::endl; } }; // global function CWinApp* AfxGetApp();
#include "Frame1.h"
extern CMyWinApp theApp;
CWinApp* AfxGetApp()
{
return theApp.m_pCurrentWinApp;
}
Frame1.h
#includeFrame1.cpp#include "MFC.h" class CMyWinApp : public CWinApp { public: CMyWinApp() { std::cout << "CMyWinApp Constructor" << std::endl; } ~CMyWinApp() { std::cout << "CMyWinApp Destructor" << std::endl; } }; class CMyFrameWnd : public CFrameWnd { public: CMyFrameWnd() { std::cout << "CMyFrameWnd Constructor" << std::endl; } ~CMyFrameWnd() { std::cout << "CMyFrameWnd Destructor" << std::endl; } };
#include "Frame1.h"
CMyWinApp theApp; // globasl object
//----------------------------------------
// main
//----------------------------------------
int main()
{
CWinApp* pApp = AfxGetApp();
return 0;
}
输出结果
CObject Constructor
CCmdTarget Constructor
CWinThread Constructor
CWinApp Constructor
CMyWinApp Constructor
CMyWinApp Destructor
CWinApp Destructor
CWinThread Destructor
CCmdTarget Destructor
CObject Destructor
1·注意历代父类构造函数和析构函数的调用顺序。
2·全局对象的构建比程序进入点要早,亦即是说,输出结果中所有构造函数输出操作都是在main函数之前完成的。
3·main 函数调用全局函数 AfxGetApp() 取得 theApp 对象指针,也是仿真 MFC 程序的手法。



