gpt4 book ai didi

arrays - 数组内的 C 联合多态性

转载 作者:行者123 更新时间:2023-12-04 12:42:34 26 4
gpt4 key购买 nike

鉴于以下情况:

typedef struct{
...
...
} A;

typedef struct{
...
...
} B;

typedef union __attribute__((transparent_union)) {
A a;
B b;
} C;

如果我声明一个函数
myMethod(C){
...
}

在没有明确转换的情况下,以下是合法的:
A myA;
B myB;

meMethod(myA);
myMethod(myB);

(来自:“ c unions and polymorphism ”)

但是,为什么不允许以下情况:
C cArray[2];
c[0]=myA;
c[1]=myB;

这会在没有显式转换的情况下产生不兼容的类型错误。有什么办法可以避免显式转换吗?

最佳答案

GCC documentation状态:

This attribute, attached to a union type definition, indicates that any function parameter having that union type causes calls to that function to be treated in a special way.



换句话说,透明度仅适用于函数参数。

关于arrays - 数组内的 C 联合多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10722647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com