gpt4 book ai didi

c++ - 嵌套类中的静态成员是否具有封闭类的静态持续时间?

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:50 26 4
gpt4 key购买 nike

如果我有嵌套类,并且这些嵌套类有静态成员,这些成员对于封闭类来说仍然是静态的吗?例如,如果我有

class Enclosing {
public:
Enclosing();
private:
class Nested {
public:
Nested();
private:
static int thing;
};
};

如果我这样做

auto A = Enclosing();
auto B = Enclosing();

AB 是否可以为 thing 设置不同的值?

最佳答案

Will A and B be able to have different values for thing?

不,它们不会有不同的值。所有实例都将看到相同的 thing 值;类的嵌套在这里没有影响。

static 成员变量“与类关联”(即与类实例关联的非静态成员)。 From cppreference ;

Static data members are not associated with any object. They exist even if no objects of the class have been defined. If the static member is declared thread_local (since C++11), there is one such object per thread. Otherwise, there is only one instance of the static data member in the entire program, with static storage duration.

Live sample .

关于c++ - 嵌套类中的静态成员是否具有封闭类的静态持续时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35546952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com