c++ - 对静态变量 c++ 的 undefined reference

标签 c++ static

您好,我在以下代码中遇到 undefined reference 错误:

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() 在你的类中 not 是静态的,你确实 not 需要将它设为 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;
};

关于c++ - 对静态变量 c++ 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16284629/

相关文章:

C++公共(public)构造函数地址

java - 每个实例记录器,不好的做法?

c++ - main函数中静态对象的理解

c++ - 如何从就地临时变量初始化非静态私有(private)模板成员变量,即不进行复制或移动?

java - Switch 语句并在静态 block 中初始化最终静态变量

flutter - Flutter/Dart:窗口小部件中的文本根据哪个屏幕调用而变化?

c++ - lib 中的 static 对所有对象都是相同的值吗?

c++ - 类模板偏特化 : compiler error

c++ - protected 成员是派生类中的 "not declared in this scope"

c++ - 为什么我在输入 typedef auto 时会出错?