为什么继承的结构成员在联合中无法访问?

Why inherited struct members are inaccessible in union?

本文关键字:访问 继承 结构 成员 为什么      更新时间:2023-10-16

>我有以下代码在编译时生成错误:

struct s { int three; };
union alias {
struct { int one; };
struct { int two; };
struct : s {};
};
int main()
{
alias a;
a.one = 1;   // OK
a.two = 2;   // OK
a.three = 3; // error: 'union alias' has no member named 'three'
return 0;
}

由于某种原因,联合中继承结构的成员无法访问。此代码的主要目的是为结构s的成员提供别名。

为什么编译器看不到继承结构的成员?有什么选项可以使它们可访问吗?

好的,经过一番挠头,我想我可以正确解释这一点。好吧,首先,这是非法的,因为Heck(tm(。

在联合中定义的struct会让编译器感到困惑。如果结构 def 后跟名称,通常会创建此类结构类型的新变量,但C++明确不允许匿名结构。如果省略该名称,则可能意味着两件事 - 要么创建匿名结构类型,然后立即删除(符合-Wpedantic警告(,要么,就像GCC似乎发生的那样,它认为它是匿名类型的匿名成员的创建,这是一个非标准扩展:

union alias {
struct { int one; };     // anonymous member of an anonymous type
struct a { int two };    // no member, just def of "struct a"
struct { int three; } b; // named (b) member of type anonymous struct
};

总而言之,你不能指望这能奏效......除非使用显式类型和数据成员名称创建联合成员:

struct s { int three; };
union alias {
struct A { int one; };
struct B { int two; };
struct C : s { };
A a;
B b;
C c;
};
int main() {
alias a;
a.a.one = 1;   // OK
a.b.two = 2;   // OK
a.c.three = 3; // OK
}

整个匿名工会成员的事情对我来说仍然有点令人费解,因为我无法在标准中找出任何可以使这项工作的东西。