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

标签 c++ inner-classes static-members

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

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/

相关文章:

c++ - 如何从 C++ 内部类引用封闭实例?

c++ - 我在 Clang 中发现错误了吗?

c++ - 填充静态 std::map 类成员变量时的声明冲突

c++ - 在 Visual Studio 中调试使用 CreateProcess 生成的进程

c++ - 我怎样才能明智地重载放置运算符 new?

java - 如何从内部 AsyncTask 访问 fragment

php - 如何使用 $this 访问静态类成员?

c++ - 链接库未在 makefile 中正确设置

c++ - 没有定义的函数声明

c++ - 如何解决由继承和嵌套类引起的这种冗余?