我在全局范围内声明了这个结构,
struct a{
int a;
int x;
union b{
int a;
int b;
int y;
};
};
然后在 main 中声明一个 union ,
union b a;
这并没有给出任何错误。但是,如果在结构定义中声明 union 'a',例如:
struct a{
int a;
int x;
union b{
int a;
int b;
int y;
}a;
};
它给出错误“重复成员 a”。 (我们在前一个案例中使用了相同的名称“a”) 为什么一个有效而另一个无效?
其次,我们如何独立使用在 struct 中声明的 union ,但不能使用任何其他整数变量,比如“x”? 比如,我可以成功执行以下操作:
union b z; //works in this case, BUT not if we declare 'z' with the definition.
z.y=6; //works
x=6; //gives error
(我知道我们在 main 内部声明 union ,但它的定义在结构内部。比如,struct.union.union_variable 是有道理的,但是直接拥有 union.union_variable 使其有点独立。不应该像'x'?)
最佳答案
It gives error "duplicate member a". (WE USED THE SAME NAME 'a' IN THE PREVIOUS CASE) Why does one work and another does not?
因为您的结构现在有两个名为 a
的成员:第一个是 int
,第二个是 b
类型(您的 > union
)。你不会惊讶地看到这不能编译:
struct a {
int a;
float a;
};
在你的情况下,你有完全相同的情况,想象你在 struct
之外定义了 b
并且你尝试像这样使用它:
struct a {
int a;
union b a;
};
Secondly, how can we use the union declared inside struct, independently, but can't use any other integer variable, say 'x'? Like, i can perform the following successfully:
x
声明在哪里?您没有任何名为 x
的局部变量(您可能有一个名为 x
的结构成员,但您需要这样的结构)。以下之一(根据您要执行的操作):
int x = 6;
struct a w;
a.x = 6;
关于c - 这个结构/union 声明有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23630030/