如果我在静态类中创建枚举,会有什么不同吗?
基本上,如果我不让所有对象都获得所有枚举值的副本?
ps:一如既往,欢迎参考您的答案......
Basically, if I don't do all objects get a copy of all the enum values?
ps: as always, references for your answer are always welcome...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 enum 关键字实际上是在定义类型,而不是像数据成员那样定义存储。
这就像定义一个内部类,如下所示:
InnerClass 定义只是一个定义。它只是定义了外部类X上下文中的类型,因此InnerClass只能称为X::InnerClass。
但它绝对不会占用类 X 的实例中的任何空间。
关于枚举的说明:枚举值实际上是整数,这些整数在代码中需要的地方使用。通常,没有所有枚举值的中央存储。枚举仅定义标记和数值之间的映射,并且在代码中使用标记的任何地方,编译器都会将其替换为数值。
With the enum keyword you are actually defining a type, not defining storage like a data member.
It's like defining an inner class, like this:
The InnerClass definition is just a definition. It just defines the type within the context of the outer class X, so InnerClass can only be referred to as X::InnerClass.
But it definitely doesn't take any space in the instances of class X.
Regarding the remark on enums: The enum values are actually integers, and these integers are used in the code where needed. Normally there is no central storage of all the enum values. The enum just defines a mapping between a token and a numerical value and everywhere the token is used in your code, the compiler replaces it with the numerical value.
您不能将嵌套类型(例如枚举)声明为静态。从句法上来说。
You cannot declare a nested type (such as enum) static. Syntactically.
你不能,这没有意义。每个实例不存储值,它们将存储恰好来自枚举值的值。
You can't, it doesn't make sense. Each instance doesn't store the values, they would store a value that happens to come from the enumerated values.
枚举不包含所有可能的值。各种可能的值仅在编译时存在于代码中。在运行时,枚举的每个实例本质上都是一个整数值。
Enums don't hold all possible values. The various possible values only exist in the code during compile time. At run time, each instance of an enum is essentially an integral value.
enum {..}
实际上并不占用程序中的任何空间。 只有声明为该枚举类型的对象才会占用任何空间。即使这样,它也不太可能比机器寄存器容纳的空间更多(因为它们与整数类型兼容)。与为该类型定义的所有枚举名称和值关联的唯一存储位置是在编译期间。在运行时,所有这些信息都是不必要的(因此不存在)。
enum {..}
s don't really take up any space in your program. Only objects declared as that enumerated type take up any space. Even then, it is unlikely to be more space than fits in a machine register (since they are comptaible with integer types).The only place there will ever be any storage associated with all the enumerated names and values defined for the type is during compilation. At runtime, all that information is unnessecary (and thus is not there).