cocos2dx运行程序实例探究
|
最近接触到cocos2dx,根据网上搜索到的资料创建出来“hello world”后,开始研究它是怎么运行的。红孩儿的文章不错,推荐读一读。 http://blog.csdn.net/honghaier/article/details/7887873 我使用的cocos2dx是2.2版本,在main.cpp中,有这么几句话让我有点费解,后面研究了下代码,算是懂了一点。 AppDelegate app;
CCEGLView* eglView = CCEGLView::sharedOpenGLView();
eglView->setViewName("testgame");
eglView->setFrameSize(480,320);
return CCApplication::sharedApplication()->run();
中间的三句话先不说,先聊聊第一句和最后一句。 第一句就是声明了一个对象,最后一句是运行。教程中在说程序运行时要调用导演类的这个方法: bool AppDelegate::applicationDidFinishLaunching() 可是究竟是怎么通过main.cpp中的那两句话调到这个方法呢? 仔细读下源代码还是比较好理解的,前提是你要晓得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其实就是第一句话声明对象的地址. 最后一句话CCApplication::sharedApplication()返回的就是刚才的静态变量sm_pSharedApplication.在看run()函数中调用: if (!applicationDidFinishLaunching()) 由于多态,就调用了子类AppDelegate 的applicationDidFinishLaunching()函数了。
特意自己写了一段验证: #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;
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
