c++ - union 内的未知成员函数

标签 c++ struct unions

我正在阅读一段代码。我相信这是在 C++ 中:

 union Float_t
 {
    Float_t(float num = 0.0f) : f(num) {}
    // Portable extraction of components.
    bool Negative() const { return (i >> 31) != 0; }
    int32_t RawMantissa() const { return i & ((1 << 23) - 1); }
    int32_t RawExponent() const { return (i >> 23) & 0xFF; }

    int32_t i;
    float f;
    #ifdef _DEBUG
    struct
    {   // Bitfields for exploration. Do not use in production code.
         uint32_t mantissa : 23;
         uint32_t exponent : 8;
         uint32_t sign : 1;
    } parts;
    #endif
};

谁能解释两件事?

1..

 Float_t(float num = 0.0f) : f(num) {}   

这句话在说什么?当 f 未定义时,f(num) 是什么意思?

2..为什么后面的代码中需要#ifdef _DEBUG和#endif?

谢谢。

最佳答案

Float_t(float num = 0.0f) : f(num) {} 

这是一个构造函数,它采用一个参数来设置 Float_t::f 的值。构造函数有一个默认参数,将 Float_t::f 设置为 0.0f

构造函数调用示例:

Float_t f1; // f1.f == 0.0f; is true
Float_t f2 = Float_t(3.f); // f2.f == 3.0f; is true

2.. Why are #ifdef _DEBUG and #endif necessary in the latter part of the code?

代码编写者将信息用于调试目的,不希望联盟的用户访问该信息。

请注意,如果在生产代码中启用,添加的信息不会影响性能或内存使用。

请注意,所有 union 成员都在相同的内存地址,f1f2 的以下信息保持不变

f1.f == 0.0f; // evaluates to true
f1.i == 0; // evaluates to true
f1.parts.mantissa == 0; // evaluates to true
f1.parts.exponent == 0; // evaluates to true
f1.parts.sign == 0; // evaluates to true

f2.f == 3.0f; // evaluates to true
f2.i == 1077936128; // evaluates to true
f2.parts.mantissa == 4194304; // evaluates to true
f2.parts.exponent == 128; // evaluates to true
f2.parts.sign == 0; // evaluates to true

sizeof(f1) == 4; // evaluates to true

reinterpret_cast<float&>(f2.i) == f2.f; // evaluates to true

编辑

上面代码中的常量值是在小端配置上获得的,声明为位字段的数据的顺序是从低位到高位

关于c++ - union 内的未知成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18343999/

相关文章:

c++ - 没有 union 的哈希码的内存地址

c++ - 数组在 C++ 中不使用大括号初始化

c++ - 为什么在这些折叠表达式中使用 std::min 是未定义的行为?

c++ - 哪个 C++ 单元测试框架不需要我将应用程序构建为库?

c++ - 从 cin 读入结构数组时终止输入

C++ 在使用嵌套 union 定义结构时需要一个表达式

c++ - 如何防止截止时间计时器调用已删除类中的函数?

c++ - 在 C++ 中初始化指针数组

c# - .NET 中用户创建的结构和框架结构之间的差异

c++ - 为什么 long long union 成员的对齐比包含的 union/struct 大?这个对吗?