初始化程序,联合的特定成员
Initialiser, specific member of a union
我感觉这个问题的答案是否定的,但是是否可以初始化联合体的特定成员?例如以下内容:
#include <cassert>
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
auto time = 20090520145024798ull;
auto large = ULARGE_INTEGER() = {
{ time }
};
assert(large.QuadPart == time);
return 0;
}
(Visual Studio 2013, Windows 10),生成编译器 "conversion from 'unsigned __int64' to 'DWORD'",暗示它将尝试将 uint64_t 塞进 DWORD。
ULARGE_INTEGER是并集:
typedef union _ULARGE_INTEGER {
struct {
DWORD LowPart;
DWORD HighPart;
} u;
ULONGLONG QuadPart;
} ULARGE_INTEGER;
在这种情况下,标准对初始化顺序有何规定?我曾希望编译器会发现 QuadPart 是要分配的适当成员。
保持简单:
ULARGE_INTEGER large;
large.QuadPart = time;
或者如果你想使用自动并在一行中初始化它,也许做一个小帮手?
inline auto MAKE_ULARGE_INTEGER(ULONGLONG t)
{
ULARGE_INTEGER result;
result.QuadPart = t;
return result;
}
auto large = MAKE_ULARGE_INTEGER(time);
对于联合,您可以使用列表初始化仅初始化第一个成员,根据 [dcl.init.aggr]:
When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer-clause
for the first non-static data member of the union. [ Example:
union u { int a; const char* b; };
u a = { 1 };
u b = a;
u c = 1; // error
u d = { 0, "asdf" }; // error
u e = { "asdf" }; // error
—end example ]
因此,在您的示例中,如下所示:
ULARGE_INTEGER large{time};
将初始化 u.LowPart
,而不是 QuadPart
,无论各种成员的类型是什么。
如果您想做任何其他事情,您必须明确说明:
ULARGE_INTEGER large;
large.QuadPart = time;
或者写一个更好的 union
类型,它实际上有一个构造函数。
我感觉这个问题的答案是否定的,但是是否可以初始化联合体的特定成员?例如以下内容:
#include <cassert>
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
auto time = 20090520145024798ull;
auto large = ULARGE_INTEGER() = {
{ time }
};
assert(large.QuadPart == time);
return 0;
}
(Visual Studio 2013, Windows 10),生成编译器 "conversion from 'unsigned __int64' to 'DWORD'",暗示它将尝试将 uint64_t 塞进 DWORD。
ULARGE_INTEGER是并集:
typedef union _ULARGE_INTEGER {
struct {
DWORD LowPart;
DWORD HighPart;
} u;
ULONGLONG QuadPart;
} ULARGE_INTEGER;
在这种情况下,标准对初始化顺序有何规定?我曾希望编译器会发现 QuadPart 是要分配的适当成员。
保持简单:
ULARGE_INTEGER large;
large.QuadPart = time;
或者如果你想使用自动并在一行中初始化它,也许做一个小帮手?
inline auto MAKE_ULARGE_INTEGER(ULONGLONG t)
{
ULARGE_INTEGER result;
result.QuadPart = t;
return result;
}
auto large = MAKE_ULARGE_INTEGER(time);
对于联合,您可以使用列表初始化仅初始化第一个成员,根据 [dcl.init.aggr]:
When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer-clause for the first non-static data member of the union. [ Example:
union u { int a; const char* b; }; u a = { 1 }; u b = a; u c = 1; // error u d = { 0, "asdf" }; // error u e = { "asdf" }; // error
—end example ]
因此,在您的示例中,如下所示:
ULARGE_INTEGER large{time};
将初始化 u.LowPart
,而不是 QuadPart
,无论各种成员的类型是什么。
如果您想做任何其他事情,您必须明确说明:
ULARGE_INTEGER large;
large.QuadPart = time;
或者写一个更好的 union
类型,它实际上有一个构造函数。