struct static member meaning/definition [closed]

本秂侑毒 提交于 2019-12-30 07:46:10

问题


struct a{static int z;}l;
(a is declared at file scope)    

I cant initialize the z using a initializer list. what does a static struct member mean?

does z(name) have external linkage and public access as well?

(I thought it meant you give it file scope and group it under a(and has public access through a object)?..why cant I initialize?)

Also....what If I had a static struct member in a class?


回答1:


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.



来源:https://stackoverflow.com/questions/19469475/struct-static-member-meaning-definition

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