struct static member meaning/definition [closed]

匆匆过客 提交于 2019-12-01 01:24:37

static member of a class / struct is a member that is not specific for a concrete instance of that class / struct. Apart from some special cases, it must almost always be explicitly initialized in one of the compilation units. Then it can be accessed using the namespace, in where it was defined:

#include <iostream>

struct a {
    static int z;
    int i;
} l;

int a::z = 0; // initialization

int main() {
    a::z = 3;
    l.i = 4;
    std::cout << a::z << ' ' << l.i;
    return 0;
}

outputs 3 4.


"I cant initialize the z using a initializer list."
That's because an initialization list is used to initialize members of a specific instance of that struct by the time they are being constructed. Static member is constructed and initialized in a different manner.

"what If I had a static struct member in a class?"
The only difference is that members defined in class are private by default, unlike struct, where it is public.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!