将{0x7fc00000}之类的内容分配给联合是什么意思?

时间:2015-03-30 22:22:48

标签: c++ c++03

我正在将一些代码从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;
};

我对工会没有太多经验,但我从here

获得了基础知识

我仍然感到困惑的是,为什么我在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:\Users\admin\kflash.cpp:55:20: note: candidates are:
C:\Users\admin\kflash.cpp:11:7: note: kt_flash::DataU::DataU()
 union DataU {
       ^
C:\Users\admin\kflash.cpp:11:7: note:   candidate expects 0 arguments, 1 provided
C:\Users\admin\kflash.cpp:11:7: note: constexpr kt_flash::DataU::DataU(const kt_flash::DataU&)
C:\Users\admin\kflash.cpp:11:7: note:   no known conversion for argument 1 from 'const char [1]' to 'const kt_flash::DataU&'
C:\Users\admin\kflash.cpp:11:7: note: constexpr kt_flash::DataU::DataU(kt_flash::DataU&&)
C:\Users\admin\kflash.cpp:11:7: note:   no known conversion for argument 1 from 'const char [1]' to 'kt_flash::DataU&&'
C:\Users\admin\kflash.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:\Users\admin\kflash.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))

2 个答案:

答案 0 :(得分:3)

这是一个初始化者,而不是作业。

在初始化程序中:

static const DataU NAN  = {0x7fc00000};

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

这在C ++标准N4296草案的第8.5.1节[dcl.init.aggr]第16节中有详细说明:

  

当使用大括号括起初始化器初始化union时,   大括号只能包含第一个 initializer-clause   联盟的非静态数据成员。

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

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

答案 1 :(得分:3)

您的代码在语法和语义上一见钟情。但是,NANmath.h中定义的标准C宏。这就是它引发奇怪错误的原因。您不应该在代码中使用此名称。

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

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

相关问题