如何对枚举使用匿名联合
How to use anonymous unions with enums?
本文关键字:枚举 更新时间:2023-10-16
当我使用匿名 union
时,如何正确访问成员数据和枚举符号?匿名联合的全部意义就在于省略了一层层次结构,使源代码不那么粗糙。我可以通过使用类型名和成员名命名union
来解决这个问题,但我不想这样做。
这是VS2012。令人惊讶的是,编译器不会接受它,但智能感知会接受它!
struct A
{
struct C {
enum {M,N,O} bar;
} c;
union {
struct B {
enum { X,Y,Z} foo;
} b;
};
};
void test(void) {
A a;
a.c.bar = A::C::M; // this works
a.b.foo = A::B::X; // this doesn't
}
给出这些消息
1>test.cpp(85): error C3083: 'B': the symbol to the left of a '::' must be a type
1>test.cpp(85): error C2039: 'X' : is not a member of 'A'
1> test.cpp(71) : see declaration of 'A'
1>test.cpp(85): error C2065: 'X' : undeclared identifier
理想情况下,我希望使用匿名/未命名结构(这在某些编译器中确实有效,即使我意识到它不是标准的c++)
struct A
{
union {
struct {
enum { X,Y,Z} foo;
int x;
} ;
struct {
enum { M,N,O} bar;
double m;
} ;
};
};
void test(void) {
A a1;
a1.bar = A::M;
a1.x = 1;
A a2;
a2.foo = A::X;
a2.m = 3.14;
}
如果我正确理解你的问题,这应该工作:
struct A
{
struct B {
enum { X,Y,Z} foo;
int x;
};
struct C {
enum { M,N,O} bar;
double m;
};
union {
B b;
C c;
};
};
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 访问在 C++ 结构中声明的枚举变量
- 枚举类'classname'的多重定义
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- typedef 枚举和枚举类有什么区别?
- 为什么我的开关/机箱在使用枚举时默认?
- 标准::可选枚举的比较运算符
- C++两个源文件之间共享的枚举的静态实例
- 打印没有铸件的枚举可以在C++中吗?
- 枚举成员与静态 int 成员?
- C++:枚举:错误:应使用标识符而不是"}"
- 带有 c++ 的枚举(输入检查)
- 在 qml 中使用 Q_ENUM 和 Q_PROPERTY 作为枚举类
- 为什么 int 类型的枚举类值不能用作 int
- 在 C++ 中输出枚举类类型的向量元素