struct静态成员的含义/定义 [英] struct static member meaning/definition

查看:72
本文介绍了struct静态成员的含义/定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我无法使用初始化列表初始化z.静态结构成员是什么意思?

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

z(name)是否也具有外部链接和公共访问权限?

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?)

还....如果我在一个类中有一个静态struct成员怎么办?

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

推荐答案

static 的成员是 class / struct 的成员不特定于该 class / struct 的具体实例.除了某些特殊情况外,几乎必须始终在其中一个编译单元中对其进行显式初始化.然后可以使用在定义位置的名称空间对其进行访问:

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;
}

输出 3 4 .

我无法使用初始化列表初始化z."
这是因为初始化列表用于在构造 struct 的特定实例的成员时对其进行初始化.静态成员的构造和初始化方式不同.

"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.

如果我在一个类中有一个静态结构成员该怎么办?"
唯一的区别是,在 class 中定义的成员默认情况下为 private ,而与 struct 不同,该成员为 public .

"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.

这篇关于struct静态成员的含义/定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆