[英]C++: static member functions and variables- redefinition of static variable?
I was trying to incorporate the Singleton design pattern into my code, but I started getting a weird error: 我试图将Singleton设计模式合并到我的代码中,但我开始遇到一个奇怪的错误:
main.obj : error LNK2005: "private: static class gameState * gameState::state" (?state@gameState@@0PAV1@A) already defined in gameState.obj
If you're not familiar with the singleton pattern, it is basically used to enforce only 1 instance of a certain object in the entire program. 如果您不熟悉单例模式,它基本上只用于在整个程序中强制执行某个对象的1个实例。 Here is the relevant code: gameState.h: 以下是相关代码:gameState.h:
class gameState
{
public:
static gameState* Instance() {return state;}
.
.
.
private:
gameState();
static gameState* state;
};
gameState* gameState::state = new gameState();
and right now I'm just using the instance of that object in the main.cpp file: 现在我只是在main.cpp文件中使用该对象的实例:
gameState *currState = gameState::Instance();
.
.
.
for_each(currState->getHumanPieces().begin(),currState->getHumanPieces().end(), drawPieces);
It would seem I am trying to redefine gameState::state, but can't figure out why... help anyone? 看起来我试图重新定义gameState :: state,但无法弄清楚为什么......帮助任何人?
that solved that, but one error still remains, which I didn't actually post before as I thought it was just part of the other one: 解决了这个问题,但仍然存在一个错误,我之前并没有真正发布,因为我认为它只是另一个错误的一部分:
error LNK2019: unresolved external symbol "private: __thiscall gameState::gameState(void)" (??0gameState@@AAE@XZ) referenced in function "void __cdecl `dynamic initializer for 'private: static class gameState * gameState::state''(void)" (??__E?state@gameState@@0PAV1@A@@YAXXZ)
any good tip on how to fix that one as well? 关于如何解决这个问题的任何好的提示?
Thanks both of you, its fixed :D 谢谢你们两位,修好了:D
You need to put the definition of the static gameState*
into exactly one source file, ie this line: 您需要将静态gameState*
的定义放入一个源文件中,即此行:
gameState* gameState::state = new gameState();
If you put it in a header which is included by multiple source files, each has a definition of gameState::state
which leads to errors at link-time. 如果你把它放在一个包含多个源文件的头文件中,每个文件都有一个gameState::state
的定义,这会在链接时导致错误。
For the follow-up problem, use Vadakkumpadaths advice: you need to provide a definition for gameState
s constructor, not only a declaration. 对于后续问题,请使用Vadakkumpadaths建议:您需要为gameState
的构造函数提供定义,而不仅仅是声明。
Add definition for your constructor to fix second linker error. 添加构造函数的定义以修复第二个链接器错误。
private:
gameState()
{
}
使用标头保护宏来重新定义问题,并明确定义您的私有构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.