具有静态成员的静态结构 [英] Static struct with static members

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

问题描述

今天我发现自己创建了一个包含 2 个整数的静态数组,并且因为它的内联初始化在 C++(不是 C++11)中是不允许的,所以我恢复使用结构类型的静态变量.

Today I found myself creating a static array of 2 ints, and because its inline initalization is not allowed in C++ (not C++11), I reverted to using a static variable of type struct.

class MyWidget {
  ...
  static const struct Margin {
    const int horizontal = 1;
    const int vertical = 1;
  } margin;

};

我注意到内部变量只对 struct Margin 的所有实例使用一次,所以我决定也将它们设为静态.

I noticed that internal variables are used only once for all instances of struct Margin, so I decided to make them static too.

class MyWidget {
  ...
  static const struct Margin {
    static const int horizontal = 1;
    static const int vertical = 1;
  } margin;

};

令我惊讶的是声明静态结构变量与具有静态成员的静态结构变量之间的区别.AFAC 静态对象在内存中只分配一次,因此无论我的成员是否为静态,Margin 结构都将只分配一次.

What wonders me is the difference between declaring a static struct variable vs. a static struct variable with static members. AFAC static objects are allocated only once in memory, therefore Margin struct wil be allocated only once no matter if my members are static or not.

我错过了什么吗?是否存在差异或仅仅是语法糖?

Do I miss something? Does there exist a difference or is it a mere syntactic sugar?

推荐答案

您似乎对静态结构体"有点困惑,因为在 C++ 中,没有静态结构体这样的东西(与 C#、其中静态类是没有全局函数这一事实的解决方法).

You seem to be a bit confused about "static structs", because in C++, there are no such things as static structs (as opposed to languages like C#, where static classes are a workaround for the fact that there are no global functions).

您正在做的是创建该类的实例,并使实例(margin)成为静态(和常量).所以你的结构不是静态的,你只是定义一个结构,并为其创建一个 static const 实例,属于 MyWidget.现在给出的两个例子之间的区别应该是很明显的.

What you're doing, is creating an instance of that class, and making the instance (margin) static (and constant). So your struct is not static, you are simply defining a struct, and making a static const instance of it, belonging to MyWidget. The difference between the two given examples now, should be quite obvious.

在第一个示例中,您正在创建一个名为 margin 的静态变量,属于 MyWidget,这意味着您可以像这样访问 horizo​​ntal 成员

In the first example, you're creating a static variable called margin, belonging to MyWidget, meaning you can access the horizontal member like so

MyWidget::margin.horizontal

其中 margin 是您创建的实例.

Where margin is the instance you have created.

然而,如果您将结构体的成员设为静态,您将无法做到这一点.相反,您必须像这样访问它们:

Whereas if you made the members of the struct static, you would not be able to do that. Instead, you would have to access them like so:

MyWidget::Margin::horizontal

其中 Marginstruct.但是请注意,在第二种情况下,不需要静态实例 margin,因为它没有与之关联的实例字段.

Where Margin is the struct. Note however, that in the second case, there is no need for the static instance margin, since it has no instance fields associated with it.

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

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