reinterpret_cast <char * =“”>(&amp; st)和(-1)* static_cast <int>是什么意思?

时间:2016-12-25 06:41:16

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

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

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;
    }

3 个答案:

答案 0 :(得分:2)

File.read(reinterpret_cast<char *> (&st), sizeof(student));直接从文件中将student结构数据读入st占用的内存。

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

此类代码仅在以二进制模式写入和读取文件时才起作用,更不用说你来创建文件并在同一台机器上读取它以确定它将按预期工作。

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

(-1)*static_cast<int>(sizeof(st));sizeof运算符的无符号结果转换为带符号的数字,并将其乘以-1

上面的行显示了所谓的 - 样式演员表。使用它们的原因是,与式演员不同,他们不会不惜任何代价进行演员表演。只有在满足铸造条件的情况下才会施放,这样更安全。

因此,将无符号转换为仅签名只需要static_cast,如果编译器静态类型检查不成立,则会失败。

reinterpret_cast是一个更强大的野兽(当你想要在某种程度上忽略类型系统时需要它),但与c风格的强制转换相比仍然有一些保护措施。

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

click here to see the image 如果您无法理解什么是File.read(reinterpret_cast<char *> (&st), sizeof(student));,则可以使用我曾经使用的方法 和, int pos=(-1)*static_cast<int>(sizeof(st));正在做并且想立即了解代码。...