如果我有这两个结构:
struct
{
int x;
} A;
struct
{
int x;
} B;然后,使A = B;导致编译错误,因为这两个匿名结构不兼容。
然而,如果我这样做了:
typedef struct
{
int x;
} S;
S A;
S B;A = B;是一种合法的转让,因为它们是兼容的。
但是为什么呢?使用typedef,我理解编译器在遇到S A和S B时会这样做
struct { int x; } A;
struct { int x; } B;所以A和B不应该兼容..。
发布于 2014-09-18 08:34:27
每个匿名结构声明都是一个不同的类型;这就是为什么在尝试将一个类型分配给另一个类型时会出现类型不匹配的原因。
但是,类型类型的别名(即已经存在的东西的新名称)声明为类型(它不创建新类型)。
类型胡枝子也是而不是--一个简单的文本替换,就像预处理宏一样。你的陈述
我理解编译器在满足
S A和S B时会这样做: 结构{ int x;} A;struct { int x;} B;
你的理解是错误的。
当您使用类型别名S时,如
S A;
S B;从定义上看,A和B两种对象的类型是相同的,并且可以将其中一个分配给另一个对象。
发布于 2014-09-18 08:36:27
这是因为C将每个未标记的struct视为一种新的struct,而不管内存布局如何。但是,如果要在链接列表中使用typedef struct { } name;,则不能使用struct。在本例中,您需要继续定义结构标记,而typedef则是标记为struct。
发布于 2014-09-18 08:36:04
struct DistanceInMeter /* Anonymous 1 */
{
int x; /* distance */
};
struct VolumeInCC /* Anonymous 2 */
{
int x; /* volume */
};
struct DistanceInMeter A;
struct VolumeInCC B;
...
A = B; /* Something is wrong here */将不同的类型等同起来并不总是有意义的,因此是不允许的。
typedef struct DistanceInMeter /* Anonymous 1 */
{
int x; /* distance */
} Dist_t;
Dist_t C, D;
...
C = D; /* Alright, makes sense */https://stackoverflow.com/questions/25907677
复制相似问题