未定义的引用静态成员



我有一个这样的代码。当运行时,返回错误:对A::x的未定义引用。我该如何解决这个问题?

#include <iostream>
using namespace std;
class A
{
private:
    static int x;
public:
    A(){
    }
    A(int t) {
        x = t;
    }
    static void f() {
        cout<< A::x;
    }
    int f2() {
        return  x;
    }
};
int main() {
    A::f();
    A a;
    a.f2();
}

您只是声明了静态变量,而没有定义它。

在类外定义:

int A::x = 0;

你需要添加

int A::x = 0; //Or any other value

最新更新