首页 > 代码库 > cocos游戏的真正入口,用C++实现的demo版本

cocos游戏的真正入口,用C++实现的demo版本

1.cocos游戏的出发点

在main函数中有一句:   return CCApplication::sharedApplication()->run();

2.经过层层深入发现,真正的入口:  bool AppDelegate::applicationDidFinishLaunching()

3.类继承关系图:

4.代码实现:

CCApplicationProtocol的头文件如下,.cpp文件为空

#pragma onceclass CCApplicationProtocol{public:    /*定义了一个虚接口,用于游戏的真正入口*/    virtual bool applicationDidFinishLaunching() = 0;};

CCApplication.h

#pragma once#include "CCApplicationProtocol.h"#include <iostream>using namespace std;class CCApplication :public CCApplicationProtocol{public:    CCApplication();    /*run方法*/    virtual int run();    /*返回静态指针*/    static CCApplication* sharedApplication();protected:    /*静态指针,用于实现单例*/    static CCApplication * sm_pSharedApplication;};

CCApplication.cpp

#include "CCApplication.h"/*cpp文件中初始化静态成员*/CCApplication * CCApplication::sm_pSharedApplication = NULL;CCApplication::CCApplication(){    /*将子类对象赋值给父类的静态指针*/    sm_pSharedApplication = this;}CCApplication* CCApplication::sharedApplication(){     /*实现单例*/    if (sm_pSharedApplication != NULL)    return sm_pSharedApplication;}int CCApplication::run(){    /*调用父类的方法,实现游戏的启动*/    applicationDidFinishLaunching();    return 0;}

AppDelegate.h

#pragma once#include "CCApplication.h"class AppDelegate :private CCApplication{public:    /*实现了继承来的祖父类方法*/    virtual bool applicationDidFinishLaunching();};

AppDelegate.cpp

#include "AppDelegate.h"/*实现了继承来的祖父类方法*/bool AppDelegate::applicationDidFinishLaunching(){    /*do somethint to iniialize the game*/    cout << "game start" << endl;    return true;}

测试代码:

#include "AppDelegate.h"int main(){    AppDelegate app;    CCApplication::sharedApplication()->run();    system("pause");    return 0;}

 

cocos游戏的真正入口,用C++实现的demo版本