c++ - 结构类型转换时信息丢失

标签 c++ data-structures struct casting

我通过将结构类型转换为整数来传递它。 在输出 printBook() 上,我通过对类型化传递的整数进行类型转换来重新获取套接字。

预期输出:-

Book id : 11
Book no of copies : 2
Book id : 12
Book no of copies : 10

实际输出

Book id : 11
Book no of copies : 0
Book id : 12
Book no of copies : 0

为什么我会丢失部分数据? 这是片段。

#define UINT16 int

typedef  unsigned int UINT32;
using namespace std;

#include <iostream>
#include <cstring>

using namespace std;

// this replicates my new Data structure
typedef struct books
{
   UINT16   book_id;
   UINT16   book_no_of_copies;
   books() : book_id(0), book_no_of_copies(0) {}
} BOOKS;

void printBook( UINT32 book );

int main( )
{
    BOOKS Book1;        // Declare Book1 of type BOOKS
    BOOKS Book2;        // Declare Book2 of type BOOKS

    // book 1 specification
    Book1.book_id = 11; // initialization
    Book1.book_no_of_copies = 2;

    // book 2 specification
    Book2.book_id = 12; // initialization
    Book2.book_no_of_copies = 10;

    // pass struct as integer
    // Print Book1 info
    printBook( *(UINT32 *)&Book1 );

    // Print Book2 info
    printBook( *(UINT32 *)&Book2 );
    getchar();
    return 0;
}

void printBook( UINT32 book )
{
    // re-convert integer to struct
    BOOKS myBook = *(BOOKS *)& book;
    cout << "Book id : " << myBook.book_id <<endl;
    cout << "Book no of copies : " << myBook.book_no_of_copies <<endl;
}

最佳答案

*(UINT32 *)&Book1 的行为在 C++ 中未定义。这是因为类型不相关。在指针大于 32 位的 64 位平台上,它会特别脆弱。

可以摆脱对void* 的转换,但这并不是真正应该在 C++ 中完成的事情。

为什么不将 printBook 移到 books struct 中?您可以在 C++ 中做到这一点:C++ struct 可以容纳成员函数 以及成员数据。 (并且在 C++ 中不需要围绕 struct 的 C 风格 typedef 习语)。

最后,#define UINT16 int 后跟 typedef unsigned int UINT32; 很奇怪。如果您的编译器支持,请考虑使用标准的固定大小(例如 std::uint32_t)。

关于c++ - 结构类型转换时信息丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35777170/

相关文章:

c++ - 如何手动销毁成员变量?

c - 该算法最坏情况下的时间复杂度是多少?

data-structures - 有些数据结构是否比其他数据结构更适合功能编程?

c - 结构的成员是结构本身

c - 使用 C,在初始化结构数组时,似乎第一列和最后一列重叠

C++字节流

c++ - 宏方法有 2 个返回值?

c++ - 检测是否安装了 Microsoft Access 驱动程序

C++ Ubuntu。使用 FFMPEG 库编译的多个 undefined reference

algorithm - 哪种数据结构可以处理这些需求?