我的头文件中有“选择”,因为你可以看到它的公共静态成员。
#ifndef SHAREDDATA_H_
#define SHAREDDATA_H_
#include "cocos2d.h"
#include "GameTrinkets.h"
using namespace std;
class SharedData{
private:
//...
//Instance of the singleton
static SharedData* m_mySingleton;
public:
//Get instance of singleton
static SharedData* sharedGameManager();
static int selection;
};
#endif /* SHAREDDATA_H_ */
我尝试访问的地方是:
所以我尝试的代码
#include "GameScene.h"
#include "GameTrinkets.h"
#include "SharedData.h"
#include <time.h>
void GameScene::mainSpriteSelection(int selection){
//1
SharedData::selection=3;
//2
SharedData::sharedGameManager()->selection=selection;
}
我得到的错误是:
[armeabi] SharedLibrary:libcocos2dcpp.so jni /../../ Classes / GameScene.cpp:41:错误:对'SharedData :: selection'的未定义引用
答案 0 :(得分:0)
错误消息告诉您需要定义静态变量selection
在GameScene.cpp文件中定义它
int GameScene::selection = 0;
答案 1 :(得分:0)
您必须将类外的静态变量(在.cpp
中)定义为
int SharedData::selection;
最小例子:
#include <iostream>
using namespace std;
struct Foo
{
static int member;
};
int Foo::member; // definition here
int main()
{
cout << Foo::member << endl;
}
否则会出现链接器错误。
答案 2 :(得分:0)
在C ++中,当您将变量声明为静态时,必须先在实现文件中重新定义它,然后才能使用该变量。例如,
//in the header file.
class foo{
public:
static int bar;
};
//in the implementation file
int foo::bar // optional initialisation.
//in the main program
//header files
int main(){
foo::bar = desired_initialisation_value; //no problem
}