关于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;

猜你喜欢

转载自blog.csdn.net/csdn_gddf102384398/article/details/83302992