C++ 对静态变量的未定义引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14331469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Undefined reference to static variable
提问by Сергей Подковырин
Possible Duplicate:
C++: undefined reference to static class member
可能的重复:
C++:对静态类成员的未定义引用
I'm using MinGW. Why static variable is not working
我正在使用 MinGW。为什么静态变量不起作用
[Linker error] undefined reference to `A::i'
#include <windows.h>
class A {
public:
static int i;
static int init(){
i = 1;
}
};
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil){
A::i = 0;
A::init();
return 0;
}
回答by billz
You only declared A::i
, need to define A::i
before using it.
您只声明了A::i
,需要A::i
在使用前定义。
class A
{
public:
static int i;
static void init(){
i = 1;
}
};
int A::i = 0;
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
A::i = 0;
A::init();
return 0;
}
Also your init() function should return a value or set to void.
此外,您的 init() 函数应该返回一个值或设置为 void。
回答by Olaf Dietsche
You have declared A::i
inside your class, but you haven't defined it. You must add a definition after class A
您已A::i
在类中声明,但尚未定义它。您必须在之后添加定义class A
class A {
public:
static int i;
...
};
int A::i;