如何在类初始值设定项中设置 union?

发布于 2024-10-21 02:47:11 字数 455 浏览 5 评论 0原文

给定一个如下所示的类和给定的联合,如何将联合初始化为正确的值?

这里尝试的是使用两种或多种不同类型作为该类的核心数据类型之一。考虑到类型是提前已知的,而不是使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

简单爱 2024-10-28 02:47:12

对于任何没有构造函数的类型,事实证明您可以在联合中初始化它。这个关于联合初始化器的答案给出了解决方案的提示:

union Union {
   int n;
   char *sz;
   Union( int n ): n( n ) {}
   Union( char *sz ): sz( sz ) {}
};

现在它按预期工作。显然,如果您知道要寻找什么。

编辑:
您还可以在类构造函数中记下 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:

union Union {
   int n;
   char *sz;
   Union( int n ): n( n ) {}
   Union( char *sz ): sz( sz ) {}
};

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文