Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 错误:联合的重新定义_C_Struct_Compiler Errors_Unions - Fatal编程技术网

C 错误:联合的重新定义

C 错误:联合的重新定义,c,struct,compiler-errors,unions,C,Struct,Compiler Errors,Unions,在以下代码中: typedef struct { union U { int a; char b; }U1; }A; typedef struct { union U { int a; char b; }U1; }B; 编译器给出了一个错误“[error]重新定义'union U'”。 但这些工会是不同结构的成员。 因

在以下代码中:

typedef struct
{
    union U
        {
            int a;
            char b;
        }U1;
}A;

typedef struct
{
    union U
        {
            int a;
            char b;
        }U1;
}B;
编译器给出了一个错误“[error]重新定义'union U'”。 但这些工会是不同结构的成员。 因此,通常不存在变量名干扰的可能性。
那么这个错误的原因是什么呢

这里没有将名称分隔为名称空间,实际上您正在尝试重新定义

片段:

typedef struct { union U { int a; char b; } U1; } A;
在以下方面没有显著差异:

union U { int a; char b; };
typedef struct { union U U1; } A;
您只需在类型中引入人工名称空间即可解决此问题:

typedef struct { union AU { int a; char b; } U1; } A;
typedef struct { union BU { int a; char b; } U1; } B;
或者,如果联合是(并将保持)相同的类型,只需定义一次:


即使您可以定义名为
U
的两个联合,它也不会非常有用。毕竟,如果您创建了一个
union U
变量,您将引用哪个联合体?如果您打算创建这样的变量,那么请为联合指定不同的名称以消除歧义。另一方面,如果你从来没有打算创建这样的变量,那么你可以考虑使用匿名联盟:

typedef struct {
    union {
        int a;
        char b;
    }U1;
}A;

typedef struct {
    union {
        int a;
        char b;
    }U1;
}B;

示例中的名称“U”是联合体的名称,“U1”是结构“A”和“B”中联合体的实例的名称。U1可以重复使用,但名称“U”在整个文件中都有作用域

你可以这样做:

typedef struct
{
    union U
        {
            int a;
            char b;
        }U1;
}A;

typedef struct
{
    union U U1;
}B;
因为A.U1和B.U1都有相同的声明。否则,你将不得不为工会使用不同的名称

或者,只需使用匿名工会(即,根本不提供工会名称):

C没有名称空间。(好吧,是的,但不是在这个粒度上)。该联盟的名称是全球性的。
typedef struct
{
    union U
        {
            int a;
            char b;
        }U1;
}A;

typedef struct
{
    union U U1;
}B;
typedef struct
{
    union
        {
            int a;
            char b;
        }U1;
}A;

typedef struct
{
    union
        {
            int a;
            char b;
        }U1;
}B;