1. 程式人生 > >關於MFC中AfxGetApp函式是怎麼得到全域性物件的指標的簡要分析

關於MFC中AfxGetApp函式是怎麼得到全域性物件的指標的簡要分析

#include <iostream>
#include <assert.h>
using namespace std;

//宣告類名
class App;
App* pThis = nullptr;

class App
{
public:
	App()
	{
		pThis = this;
		cout << "App類的建構函式被呼叫" << endl;
	}

	virtual ~App(){}

	virtual void InitInstance()
	{
		cout << "App類的InitInstance函式被呼叫" << endl;
	}
};

App* GetApp()
{
	return pThis;
}

int main()
{
	//在main函式中呼叫全域性函式來獲取指向應用程式例項的指標,利用此指標,根據多型性原理,即將使用者與系統框架關聯起來
	App* pApp = GetApp();
	assert(pApp != nullptr);

	pApp->InitInstance();

	getchar();
	return 0;
}

//在使用時,使用者是通過派生App類得到一個MyApp類,然後例項化一個MyApp的全域性物件
class MyApp :public App
{
public:
	MyApp()
	{
		cout << "MyApp類的建構函式被呼叫" << endl;
	}

	~MyApp(){}

	void InitInstance()
	{
		cout << "MyApp類的InitInstance函式被呼叫" << endl;
	}

	//這是MyApp類獨有的方法
	void Method()
	{
		cout << "MyApp類的Method方法被呼叫" << endl;
	}
};

MyApp theApp;