未定义对静态变量C ++的引用

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;
};

我不需要static foo()函数。 如何在类的非static方法中访问类的static变量?


I don't want a static foo() function

好吧,foo()在您的类中不是静态的,并且不需要将其设置为static即可访问类的static变量。

您要做的只是为静态成员变量提供一个定义:

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;
};


代码正确,但是不完整。 类Helloworld声明了其静态数据成员x,但没有该数据成员的定义。 在您需要的源代码中

1
int Helloworld::x;

或者,如果0不是适当的初始值,则添加一个初始化程序。