将类似{0x7fc00000}的东西分配给并集意味着什么

What does assigning something like {0x7fc00000} to a union mean?

本文关键字:分配 什么 意味着 0x7fc00000      更新时间:2023-10-16

我正在将一些代码从Visual studio移植到mingw。在解决了一些问题后,我发现了以下问题。我得到错误

 error: no matching function for call to 'DataU::DataU(const char [1])'
 static const DataU NAN  = {0x7fc00000};
                    ^

这是我正在使用的代码

static const DataU NAN  = {0x7fc00000};

这就是数据结构

union DataU {
    uint32_t u;
    float f;
};

我在工会方面没有太多经验,但我从这里学到了的基本知识

我仍然很困惑,为什么我在GCC的这一陈述中出错。

 static const DataU NAN  = {0x7fc00000};

据我所知,应该调用DataU的复制构造函数。但是,该联合没有自定义的复制构造函数。这是C++03,我不明白为什么这里使用{}。任何关于我如何解决这个问题的建议都将不胜感激。

更新:我真的不确定这个错误是从哪里来的。然而,我希望这个输出有助于问题

: error: no matching function for call to 'kt_flash::DataU::DataU(const char [1])'
 static const DataU NAN  = {0x7fc00000};
                    ^
C:Usersadminkflash.cpp:55:20: note: candidates are:
C:Usersadminkflash.cpp:11:7: note: kt_flash::DataU::DataU()
 union DataU {
       ^
C:Usersadminkflash.cpp:11:7: note:   candidate expects 0 arguments, 1 provided
C:Usersadminkflash.cpp:11:7: note: constexpr kt_flash::DataU::DataU(const kt_flash::DataU&)
C:Usersadminkflash.cpp:11:7: note:   no known conversion for argument 1 from 'const char [1]' to 'const kt_flash::DataU&'
C:Usersadminkflash.cpp:11:7: note: constexpr kt_flash::DataU::DataU(kt_flash::DataU&&)
C:Usersadminkflash.cpp:11:7: note:   no known conversion for argument 1 from 'const char [1]' to 'kt_flash::DataU&&'
C:Usersadminkflash.cpp:55:25: error: expected ',' or ';' before '=' token
 static const DataU NAN  = {0x7fc00000};
                         ^
In file included from C:/mingw64/x86_64-w64-mingw32/include/d3dx9math.h:26:0,
                 from C:/mingw64/x86_64-w64-mingw32/include/d3dx9.h:31,
                 from C:/mingw64/x86_64-w64-mingw32/include/d3dx9math.h:21,
                 from ./ktafx.h:36,
                 from <command-line>:0:
C:Usersadminkflash.cpp:59:25: error: no match for call to '(const kt_flash::DataU) (const char [1])'
 const float FLOAT_NAN = NAN.f;
                         ^
Process terminated with status 1 (0 minute(s), 7 second(s))
3 error(s), 3 warning(s) (0 minute(s), 7 second(s))

您的代码乍一看在语法和语义上都很好。然而,NAN是在math.h中定义的标准C宏。这就是它触发奇怪错误的原因。您不应该在代码中使用此名称。

如果NAN被其他名称替换,则GCC可以很好地编译代码。但是,一旦您将其称为NAN并包含cmath(或math.h),它就会触发错误。在我的实验中,错误信息是不同的。

将名称从NAN更改为其他名称。

这是一个初始值设定项,而不是赋值。

在类似的初始化器中

static const DataU NAN  = {0x7fc00000};

0x7fc00000初始化联合的第一个声明成员——在本例中为u

这在C++标准N4296草案第8.5.1节[dcl.init.agr]第16段中有规定:

当使用包含大括号的初始值设定项初始化并集时大括号应仅包含第一个的初始值设定项子句联合的非静态数据成员。

我希望该标准的其他版本中也有相同的措辞(C标准中也有类似的措辞)。

但我认为错误消息的原因是您使用了标识符NAN。这是在<cmath><math.h>中定义的宏;它扩展为表示浮点NaN(非数字)的表达式。更改标识符可能会解决问题。(我看到了[AnT的回答](https://stackoverflow.com/a/29357570/827263)我之前提到过这个。)