C++ 在 class 中声明一个静态对象

C++ declaring a static object in a class

我正在尝试声明我在不同的 class B 中编写的 class A 的静态对象,如下所示:

class A // just an example
{
    int x;
public:
    A(){ x = 4; }
    int getX() { return x; }
};

class B
{
    static A obj1;  // <- Problem happens here
public:
    static void start();
};

int main()
{
    B::start();
}

void B::start()
{
    int x = obj1.getX();
}

我想要实现的是让 B::start() 中的 int x 等于 class A 中的 int x (4).

在过去的一个小时里,我尝试用谷歌搜索所有这些内容,我只知道 C++ 不允许静态对象的声明。对吗?

如果是这样,这是我的问题。我怎样才能得到相同的结果?我可用的解决方法是什么?请记住,我的其余代码取决于 class B 中的静态函数。

错误

error LNK2001: unresolved external symbol "private: static class A B::obj1"

谢谢!

你应该初始化static var,代码:

class A // just an example
{
    int x;
public:
    A(){ x = 4; }
    int getX() { return x; }
};

class B
{
    static A obj1;  // <- Problem happens here
public:
    static void start();
};

A B::obj1; // init static var

int main()
{
    B::start();
}

void B::start()
{
    int x = obj1.getX();
}

正如thinkerou所说,你需要包含变量的声明:

A B::obj1;

对于普通的非静态成员变量,您不需要此步骤,因为变量是在幕后作为构造函数的一部分声明的。然后将这些变量绑定到您刚刚构建的 class 的实例。但是静态变量不绑定到 class 的任何实例;它们由 class 的所有实例共享。所以构造函数无法正确处理它们。

C++ 通过让您手动声明(并可选地初始化)任何静态成员变量来解决这个问题。根据它们的声明位置,它们通常在您的 main() 函数启动之前构建,因此它们可以立即使用。