@H_301_0@我使用的cocos2dx是2.2版本,在main.cpp中,有这么几句话让我有点费解,后面研究了下代码,算是懂了一点。
AppDelegate app; CCEGLView* eglView = CCEGLView::sharedOpenGLView(); eglView->setViewName("testgame"); eglView->setFrameSize(480,320); return CCApplication::sharedApplication()->run();
中间的三句话先不说,先聊聊第一句和最后一句。 @H_301_0@第一句就是声明了一个对象,最后一句是运行。教程中在说程序运行时要调用导演类的这个方法: @H_301_0@bool AppDelegate::applicationDidFinishLaunching()
@H_301_0@可是究竟是怎么通过main.cpp中的那两句话调到这个方法呢? @H_301_0@仔细读下源代码还是比较好理解的,前提是你要晓得this指针和虚函数。
AppDelegate 派生于类<pre name="code" class="cpp">CCApplication第一句AppDelegate app; 声明实例的时候会先进入AppDelegate父类CCApplication构造函数,CCApplication构造函数是这样的:
m_hInstance = GetModuleHandle(NULL); m_nAnimationInterval.QuadPart = 0; CC_ASSERT(! sm_pSharedApplication); sm_pSharedApplication = this;
是把this指针保存到了静态变量sm_pSharedApplication中。玄机就在这里,这个this其实就是第一句话声明对象的地址. @H_301_0@最后一句话CCApplication::sharedApplication()返回的就是刚才的静态变量sm_pSharedApplication.在看run()函数中调用: @H_301_0@if (!applicationDidFinishLaunching())
{
return 0;
}
@H_301_0@由于多态,就调用了子类AppDelegate 的applicationDidFinishLaunching()函数了。 @H_301_0@
@H_301_0@特意自己写了一段验证:
#include <iostream> using namespace std; class CBase { public: CBase(); ~CBase(); virtual void myPrint(); static CBase* GetInstance(); virtual void run(); protected: static CBase* m_instance; }; CBase* CBase::m_instance = NULL; CBase::CBase() { m_instance = this; cout<<typeid(this).name()<<endl; } CBase::~CBase() { } void CBase::myPrint() { cout<<"CBase"<<endl; } void CBase::run() { myPrint(); } CBase* CBase::GetInstance() { return m_instance; } class Dervice : public CBase { public: Dervice(); ~Dervice(); virtual void myPrint(); /*virtual void run(); protected: int nTest;*/ }; Dervice::Dervice() { cout<<typeid(this).name()<<endl; } Dervice::~Dervice() { } void Dervice::myPrint() { cout<<"Dervice"<<endl; } //void Dervice::run() //{ // cout<<"Dervice::run()"<<endl; //} int main( int _Argc,char* argv[]) { Dervice app; CBase::GetInstance()->run(); return 0; }