您好,我在以下代码中遇到 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/