【问题标题】:What does reinterpret_cast<char *>(&st) and (-1)*static_cast<int> mean?reinterpret_cast<char *>(&st) 和 (-1)*static_cast<int> 是什么意思?
【发布时间】:2017-05-10 04:57:06
【问题描述】:

此处的代码用于创建学生成绩单项目。在尝试理解时,我们无法弄清楚以下代码的用途和功能:

File.read(reinterpret_cast<char *> (&st), sizeof(student));

int pos=(-1)*static_cast<int>(sizeof(st));

File.read(reinterpret_cast<char *> (&st), sizeof(student));
if(st.retrollno()==n)
    {
    st.showdata();
    cout<<"\n\nPlease Enter The New Details of student"<<endl;
        st.getdata();
            int pos=(-1)*static_cast<int>(sizeof(st));
            File.seekp(pos,ios::cur);
            File.write(reinterpret_cast<char *> (&st), sizeof(student));
            cout<<"\n\n\t Record Updated";
            found=true;
    }

【问题讨论】:

  • 学生是什么?此代码将其读取为原始二进制文件。如果学生类型不是标准布局,则为 UB。它也有字节序的问题
  • 您提出问题的方式表明您并不真正了解reinterpret_caststatic_cast 的含义。

标签: c++ pointers reinterpret-cast static-cast


【解决方案1】:

它乘以 - 1 以返回 1 个位置。由于 c++ 中的 sizeof 函数返回一个无符号整数,因此 static_cast 会将无符号整数转换为有符号整数,然后将其乘以 - 1,因此位置为负,因此指针将转到所需位置并停留在那里,这将允许您修改数据.

【讨论】:

    【解决方案2】:

    如果您无法理解File.read(reinterpret_cast&lt;char *&gt; (&amp;st), sizeof(student)); 是什么,您可以使用我使用过的方法 和, int pos=(-1)*static_cast&lt;int&gt;(sizeof(st)); 正在做并想立即了解代码....

    【讨论】:

    • 欢迎来到 Stack Overflow。尽管这可能是该问题的正确答案,但张贴图片和快速线路可能对提问者没有帮助。请编辑您的答案,以格式正确的方式包含代码,并进行解释。您的回答将来可能对遇到同样问题的人有用。
    【解决方案3】:

    File.read(reinterpret_cast&lt;char *&gt; (&amp;st), sizeof(student));直接从文件中读取student结构体数据到st占用的内存中。

    强制转换是因为read 需要char*,这就是将一种类型的指针转​​换为完全不相关类型的指针的方式。

    此类代码仅在以二进制模式写入和读取文件时才有效,更不用说您几乎必须创建文件并确定在完全相同的机器上读取它它会按预期工作。

    即便如此,如果结构包含指针,它也可能注定要失败。


    (-1)*static_cast&lt;int&gt;(sizeof(st));sizeof 运算符的无符号结果转换为有符号数,并乘以-1


    上面的行具有所谓的 样式转换。使用这些的原因是,与 风格的演员表不同,他们不会不惜一切代价进行演员表。只有满足施法条件才会施法,安全得多。

    因此将 unsigned 转换为 signed 只需要 static_cast,如果编译器静态类型检查不成立,则会失败。

    reinterpret_cast 是一个更强大的野兽(当你想稍微忽略类型系统时需要它),但与 c 样式转换相比仍然有一些保护措施。

    【讨论】:

    • 为什么 write 期望 const char*read 期望 char
    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    相关资源
    最近更新 更多