对静态变量 c++ 的未定义引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16284629/
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 c++
提问by Tooba Iqbal
Hi i am getting undefined reference error in the following code:
嗨,我在以下代码中收到未定义的引用错误:
class Helloworld{
public:
static int x;
void foo();
};
void Helloworld::foo(){
Helloworld::x = 10;
};
I don't want a staticfoo()function. How can I access staticvariable of a class in non-staticmethod of a class?
我不想要一个staticfoo()函数。如何static在类的非static方法中访问类的变量?
回答by Andy Prowl
I don't want a
staticfoo()function
我不想要一个
staticfoo()功能
Well, foo()is notstatic in your class, and you do notneed to make it staticin order to access staticvariables of your class.
那么,foo()是不是在你的类静态的,你就不会需要使它static以访问static类的变量。
What you need to do is simply to provide a definitionfor your static member variable:
您需要做的只是为您的静态成员变量提供一个定义:
class Helloworld {
public:
static int x;
void foo();
};
int Helloworld::x = 0; // Or whatever is the most appropriate value
// for initializing x. Notice, that the
// initializer is not required: if absent,
// x will be zero-initialized.
void Helloworld::foo() {
Helloworld::x = 10;
};
回答by Pete Becker
The code is correct, but incomplete. The class Helloworldhas a declarationof its static data member x, but there is no definitionof that data member. Somehwere in your source code you need
代码是正确的,但不完整。该类Helloworld有其静态数据成员的声明x,但没有该数据成员的定义。你需要的源代码中有一些东西
int Helloworld::x;
or, if 0 isn't an appropriate initial value, add an initializer.
或者,如果 0 不是合适的初始值,则添加一个初始值设定项。

