如果多个 类 有一个共同的静态变量,它们是否共享(在同一范围内?)

If multiple classes have a static variable in common, are they shared (within the same scope?)

我有以下示例代码:

class A {
    public:
        static int a;
};
int A::a = 0;

class B {
    public:
        static A a1;
};
A B::a1;

class C {
    public:
        static A a1;
};
A C::a1;


int main(int argc, const char * argv[]) {
    C::a1.a++;
    B::a1.a++;
    std::cout << B::a1.a << " " << C::a1.a << std::endl;
    return 0;
}

Class B 和 C 有 class A 作为静态成员变量。

我希望程序打印“1 1”,但它却打印“2 2”。

如果多个 class 有一个共同的静态变量,它们是否共享(在同一范围内?)

static members属于class,与对象无关。

Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.

对于您的代码,只有一个 A::a,它独立于 B::a1C::a1(它们是 class A 的对象)。所以 B::a1.aC::a1.a 都指的是 A::a.

您在这里查看的不是多个 类。 B::a1C::a1 都是 A 类型。 A 有一个静态变量 a,您访问了两次。如果你还写了 A::a++,你的程序会打印 3 3

稍微修改您的示例:

struct A
{
    static int a;
    int b;
};
int A::a;

struct B
{
    static A a1;
};
A B::a1{0};

struct C
{
    static A a2;
};
A C::a2{0};

和用户代码:

B::a1.a = 1; // A's static variable changed
B::a1.b = 2; // B's A's b changed to 2
cout << B::a1.a << ",  " << B::a1.b << endl;
cout << C::a2.a << ",  " << C::a2.b << endl;

它将打印:

1, 2
1, 0

那是因为所有 A 共享 a,但所有 A 都有自己的 bCB 都有自己的 A (它们分别在其类型的对象之间共享)

B 和 C 都有 A 的静态实例,它们是 A 的独立实例,并且也会有其成员的不同独立实例。但是,A::a 是一个在 A 的所有实例之间共享的静态变量,因此:

&B::a1 != &C::a1 (两个a1是分开的)

但是

&B::a1.a == &C::a1.a(即所有 A::a 都是相同的,无论 A 的 'enclosing' 实例如何)