如何确定输出时使用哪种类型的联合?
我在结构中使用了一个联合类型来定义这个人是学生还是职员。当我试图输出struct数组中的信息时,我发现很难找出这个人是什么类型的人,而不是输出更多的信息。不要告诉我停止使用工会,对不起,我被要求这样做。 赫斯是我的简单的数据结构:如何确定输出时使用哪种类型的联合?
typedef union student_or_staff{
char *program_name;
char *room_num;
}student_or_staff;
typedef struct people{
char *names;
int age;
student_or_staff s_or_s;
}people[7];
这是不可能做到这一点在C,但作为一种解决方法,你可以这样
enum { student_type, staff_type } PEOPLE_TYPE;
typedef union student_or_staff{
char *program_name;
char *room_num;
}student_or_staff;
typedef struct people{
char *names;
int age;
student_or_staff s_or_s;
PEOPLE_TYPE people_type;
}people[7];
然后你只需设置沿着你的工会添加类型与你的联合,当你分配你的结构。
---------------------------- thanks -------------------- ------------- – NUO
要知道存储在union
中的内容的唯一方法是将此信息包含在其他某个地方。
还有当你处理的union
秒的阵列中发生两种常见的情况(或持有struct
个union
):
- 所有
union
S IN数组持有相同类型或 - 每个
union
可以保持其自己的类型。
当阵列中的所有union
都保持相同类型时,指示保持的类型为union
的单个变量就足够了。
当每个union
可以保持不同类型时,常用的方法是将其包装在struct
中,并添加一个标志,指示设置union
的方式。使用你的例子,该标志应该被添加到struct people
,像这样:
enum student_staff_flag {
student_flag
, staff_flag
};
typedef struct people{
char *names;
int age;
enum student_staff_flag s_or_s_flag;
student_or_staff s_or_s;
}people[7];
---------------------------- thanks ------- -------------------------- – NUO
这不是'硬',这是不可能的。为'student_or_staff'添加一个标志来指示什么是什么。 – usr2564301
你不能做这种开箱即用的东西。 – Linus
如果你被告知要这样做,而这是一个练习,我会很好奇,看看有什么精确的指示 – Lovy