Undefined reference to static variable c++
嗨,我在以下代码中收到未定义的参考错误:
1 2 3 4 5 6 7 8 | class Helloworld{ public: static int x; void foo(); }; void Helloworld::foo(){ Helloworld::x = 10; }; |
我不需要
I don't want a
static foo() function
好吧,
您要做的只是为静态成员变量提供一个定义:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; }; |
代码正确,但是不完整。 类
1 | int Helloworld::x; |
或者,如果0不是适当的初始值,则添加一个初始化程序。