C ++联合,Struct,成员类型 [英] C++ Union, Struct, Member type
问题描述
如果我有一个类:
class Odp
{
int i;
int b;
union
{
long f;
struct
{
WCHAR * pwszFoo;
HRESULT hr;
};
};
}
联盟意味着在列出的所有值中,一次采取这些值之一?在访问这些变量方面如何工作?如何直接访问 hr
?如果我设置 hr
,如果我尝试访问 f
会发生什么?
union U {
int a;
char c;
};
那么:
U u;
u.a = 1;
int n = u.a;
u.c = 2;
char c = u.c;
可以,但是:
U u;
u.a = 1;
char c = u.c;
不是。但是,有大量的现有代码,说两个都可以。在任何情况下,都不会为无效访问抛出异常。
基本上,如果你发现自己在C ++代码中使用联合来处理除了C库之外的东西,那就是错误的。
If I have a class:
class Odp
{
int i;
int b;
union
{
long f;
struct
{
WCHAR* pwszFoo;
HRESULT hr;
};
};
}
Union means that, of all values listed, it can only take on one of those values at a time? How does that work in terms of accessing these variables? How would I access hr
directly? If I set hr
, what happens if I try to access f
?
This is a very fraught area in the C++ standard - basically a union instance, per the standard can only be treated at any one time as if it contained one "active" member - the last one written to it. So:
union U {
int a;
char c;
};
then:
U u;
u.a = 1;
int n = u.a;
u.c = 2;
char c = u.c;
is OK, but:
U u;
u.a = 1;
char c = u.c;
is not. However, there are vast volumes of existing code that say that both are OK. and in neither, or any, case will an exception be thrown for an "invalid" access. The C++ language uses exceptions exceptionally (!) sparingly.
Basically, if you find yourself using unions in your C++ code to deal with anything but C libraries, something is wrong.
这篇关于C ++联合,Struct,成员类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!