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

Undefined reference to static variable c++

本文关键字:未定义 引用 c++ 静态 变量      更新时间:2023-10-16

嗨,我在下面的代码中得到未定义的引用错误:

class Helloworld{
  public:
     static int x;
     void foo();
};
void Helloworld::foo(){
     Helloworld::x = 10;
};

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

我不想要static foo()函数

好吧,foo()在你的类中是不是静态的,你不需要使它成为static以便访问你的类的static变量。

你需要做的只是为你的静态成员变量提供一个定义:
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声明,但是没有定义。在源代码中需要

int Helloworld::x;

或者,如果0不是合适的初始值,则添加初始化器

老问题,但是;

由于c++17,你可以声明static成员inline并在class的体中实例化它们,而不需要out-of-class定义:

class Helloworld{
  public:
     inline static int x = 10;
     void foo();
};