说明:1. 在本文中,我们在析构函数中用printf代替cout, 至于具体原因,之前的博文已经讲过,这里不再赘述。
2. 仿真是在Windows Console上进行的。
在仿真MFC类层次结构之前,我们先来复习一下与this指针相关的一个典型程序:
#include <iostream>
using namespace std;
class Base
{
public:
Base *pB;
Base()
{
pB = this;
cout << "Base Constructor" << endl;
}
virtual void fun()
{
cout << "Base fun" << endl;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived Constructor" << endl;
}
virtual void fun()
{
cout << "Derived fun" << endl;
}
};
Derived d;
Base *getPointer()
{
return d.pB;
}
int main()
{
Base *p = getPointer();
p->fun();
return 0;
}
结果为:
Base Constructor
Derived Constructor
Derived fun
可见,this绑定的是派生类Derived的对象。
下面,我们来仿真MFC类的层次结构图(在Windows Console上仿真),程序如下:
#include <iostream>
using namespace std;
// MFC的类程序
class CObject
{
public:
CObject()
{
cout << "CObject Constructor \n";
}
~CObject()
{
printf("CObject Destructor \n");
}
};
class CCmdTarget : public CObject
{
public:
CCmdTarget()
{
cout << "CCmdTarget Constructor \n";
}
~CCmdTarget()
{
printf("CCmdTarget Destructor \n");
}
};
class CWinThread : public CCmdTarget
{
public:
CWinThread()
{
cout << "CWinThread Constructor \n";
}
~CWinThread()
{
printf("CWinThread Destructor \n");
}
};
class CWinApp : public CWinThread
{
public:
CWinApp* m_pCurrentWinApp;
CWinApp()
{
cout << "CWinApp Constructor \n";
m_pCurrentWinApp = this; // this绑定全局对象theApp
}
~CWinApp()
{
printf("CWinApp Destructor \n");
}
};
// 应用程序
class CMyWinApp : public CWinApp
{
public:
CMyWinApp()
{
cout << "CMyWinApp Constructor \n";
}
~CMyWinApp()
{
printf("CMyWinApp Destructor \n");
}
};
CMyWinApp theApp; // 全局对象
CWinApp* AfxGetApp() // 全局函数
{
return theApp.m_pCurrentWinApp;
}
int main()
{
CWinApp* pApp = AfxGetApp(); // pApp绑定了theApp对象
return 0;
}
结果为:
CObject Constructor
CCmdTarget Constructor
CWinThread Constructor
CWinApp Constructor
CMyWinApp Constructor
CMyWinApp Destructor
CWinApp Destructor
CWinThread Destructor
CCmdTarget Destructor
CObject Destructor
对比上述程序和MFC的实际框架,就发现两者有异曲同工之妙。
为了进一步证实pApp的确是绑定了theApp对象,我们来测试一下,程序如下:
#include <iostream>
using namespace std;
// MFC的类程序
class CObject
{
public:
virtual void print()
{
cout << "CObject" << endl;
}
};
class CCmdTarget : public CObject
{
public:
virtual void print()
{
cout << "CCmdTarget" << endl;
}
};
class CWinThread : public CCmdTarget
{
public:
virtual void print()
{
cout << "CWinThread" << endl;
}
};
class CWinApp : public CWinThread
{
public:
CWinApp* m_pCurrentWinApp;
CWinApp()
{
m_pCurrentWinApp = this; // this绑定全局对象theApp
}
virtual void print()
{
cout << "CWinApp" << endl;
}
};
// 应用程序
class CMyWinApp : public CWinApp
{
public:
virtual void print()
{
cout << "CMyWinApp" << endl;
}
};
CMyWinApp theApp; // 全局对象
CWinApp* AfxGetApp() // 全局函数
{
return theApp.m_pCurrentWinApp;
}
int main()
{
CWinApp* pApp = AfxGetApp(); // pApp指向了theApp对象
pApp->print();
return 0;
}
结果为:
CMyWinApp