我有以下代码:
namespace GameStatus{
static std::vector<SavePoint>savePoints;
}
ASavePoint
是:
class SavePoint{
public:
int distance;
int score;
SavePoint(int d,int s){
distance = d;
score = s;
};
};
问题是,即使GameStatus::savePoints
是static
,向量也似乎包含元素或不包含元素,这取决于调用方是谁。
例如,如果我有一个添加保存点的类:
class Game{
void addSavePoint(){
SavePoint savepoint(12,10);
GameStatus::savePoints.push_back(savepoint);
}
void testView(){
if(!GameStatus::savePoints.empty()){
Log("There is a save point"); // Can see that savePoints is not empty in the debugger. Everything looks ok here.
}
}
}
但是,如果我还有其他课程:
class Foo{
void something(){
if(GameStatus::savePoints.empty()){ // In this class it appears that the vector is empty.
//..do something.
}
}
}
我有一个游戏循环,该循环在Game和Foo中交替执行代码,似乎其中Game
GameStatus::savePoints
有一个savePoint(不为空),而在Foo中则没有(显示为空)。对我而言,这savePoints
是没有意义的,因为它是静态的。因此,这两个类都应访问相同的对象。
GameStatus::savePoints
如果不同的类,为什么看起来具有不同的值?
static
关键字在C ++中有两个含义。
解决方案:应该将声明放在带有extern
存储说明符而不是的标头中static
,因为您希望它是全局的。之后,您应该将定义放到一个.cpp文件中,该文件是一个编译单元/对象。这样,您将拥有向量的一个实例,可从包括头文件在内的所有其他编译单元访问该向量。
头文件:
namespace GameStatus{
extern std::vector<SavePoint> savePoints;
}
cpp文件:
std::vector<SavePoint> GameStatus::savePoints;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句