如何检查联合中当前使用的是什么类型? [英] How to check what type is currently used in union?

查看:26
本文介绍了如何检查联合中当前使用的是什么类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个工会:

typedef union someunion {
    int a;
    double b;
} myunion;

是否可以在我设置后检查联合中的类型,例如a=123?我的方法是将这个联合添加到某个结构中,并在它是 int 时将 uniontype 设置为 1,当它是 double 时将 uniontype 设置为 2.

Is it possible to check what type is in union after I set e.g. a=123? My approach is to add this union to some structure and set uniontype to 1 when it's int and 2 when it's double.

typedef struct somestruct {
    int uniontype
    myunion numbers;
} mystruct;

有没有更好的解决方案?

Is there any better solution?

推荐答案

有没有更好的解决方案?

Is there any better solution?

不,您展示的解决方案是最好的(也是唯一的)解决方案.union 非常简单 - 它们不会跟踪"您分配给什么的内容.他们所做的只是让您为所有成员重用相同的内存范围.它们不提供除此之外的任何其他内容,因此将它们包含在 struct 中并使用类型"字段进行跟踪正是正确的做法.

No, the solution that you showed is the best (and the only) one. unions are pretty simplistic - they do not "track" what you've assigned to what. All they do is let you reuse the same memory range for all their members. They do not provide anything else beyond that, so enclosing them in a struct and using a "type" field for tracking is precisely the correct thing to do.

这篇关于如何检查联合中当前使用的是什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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