如何在类初始值设定项中设置 union?
给定一个如下所示的类和给定的联合,如何将联合初始化为正确的值?
这里尝试的是使用两种或多种不同类型作为该类的核心数据类型之一。考虑到类型是提前已知的,而不是使用 void*,构造将要使用的类型的联合。问题是在实例化类时如何初始化正确的联合成员。这些类型不是多态的,因此通常的继承模型似乎不合适。一些初始化正确的工会成员的幼稚尝试毫无结果。
union Union {
int n;
char *sz;
};
class Class {
public:
Class( int n ): d( 1.0 ), u( n ) {}
Class( char *sz ): d( 2.0 ), u( sz ) {}
....
double d;
Union u;
};
在寻找解决方案后,答案变得显而易见,并且可能是这个答案存储库的一个很好的解决方案,所以我将其包含在下面。
Given a class such as the one below and the given union, how does one initialize the union to the correct value?
What is being attempted here is to use two or more different types as one of the core data types for the class. Instead of using void*, given that the types are known ahead of time a union of the types that are going to be used is constructed. The problem is how to initialize the correct union member when the class is instantiated. The types are not polymorphic, so the usual inheritance model did not seem appropriate. Some naive attempts to initialize the correct union member led nowhere.
union Union {
int n;
char *sz;
};
class Class {
public:
Class( int n ): d( 1.0 ), u( n ) {}
Class( char *sz ): d( 2.0 ), u( sz ) {}
....
double d;
Union u;
};
After scouring for a solution, an answer became obvious, and could possibly be a good solution for this repository of answers, so I include it below.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于任何没有构造函数的类型,事实证明您可以在联合中初始化它。这个关于联合初始化器的答案给出了解决方案的提示:
现在它按预期工作。显然,如果您知道要寻找什么。
编辑:
您还可以在类构造函数中记下 union 中使用的类型,通常使用 int 等。
For any type that does not have a constructor, it turns out that you can initialized it in a union. This answer on union initializers gives a hint to the solution:
Now it works as expected. Obvious, if you knew what to look for.
Edit:
You can also note the type used in the union in your class constructor, typically with an int or the like.