自己动手写cocos2dx游戏引擎(二)——applicationDidFinishLaunching

时间:2023-02-08 00:14:59

上一节中,我们最终调用了Application的run方法。

在run方法中,调用了applicationDidFinishLaunching方法,这个方法在哪里呢?

可以看到在Application中并没有实现这个方法,这个方法来自Application的基类ApplicationProtocol。

ApplicationProtocol中,将applicationDidFinishLaunching声明为纯虚函数,最终的实现放到了AppDelegate中。

修改上一节中的代码。

// AppDelegate.h

#ifndef __APP_DELEGATE__
#define __APP_DELEGATE__

#include "Application.h"

#include <iostream>

class AppDelegate: private Application {
public:
virtual bool applicationDidFinishLaunching() {
std::cout << "delegate applicationDidFinishLaunching" << std::endl;
return true;
}
};

#endif

添加了对纯虚函数applicationDidFinishLaunching的实现,在其中打印了一句话。


// Application.h

#ifndef __APPLICATION__                                                                                               
#define __APPLICATION__

#include "ApplicationProtocol.h"

#include <iostream>

class Application: public ApplicationProtocol {
public:
Application() {
sm_pSharedApplication = this;
}
static Application* getInstance() {
return sm_pSharedApplication;
}
int run() {
std::cout << "App run ..." << std::endl;
if (!applicationDidFinishLaunching()) {
return 1;
}
}
protected:
static Application * sm_pSharedApplication;
};

Application * Application::sm_pSharedApplication = 0;

#endif

在Application中添加了对applicationDidFinishLaunching的调用,并让他继承自抽象类ApplicationProtocol。

// ApplicationProtocol.h

class ApplicationProtocol {                                                                                           
public:
virtual ~ApplicationProtocol(){}
virtual bool applicationDidFinishLaunching() = 0;
};
在这个抽象类中声明纯虚函数applicationDidFinishLaunching。

编译运行可以看到最终输出:

App run ...
delegate applicationDidFinishLaunching


附代码:demo2