Amr*_*CSE -1 c++ pointers static-cast reinterpret-cast
此处的代码用于创建学生成绩单项目。在尝试理解时,我们无法弄清楚以下代码的用途和功能:
File.read(reinterpret_cast<char *> (&st), sizeof(student));
int pos=(-1)*static_cast<int>(sizeof(st));
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
File.read(reinterpret_cast<char *> (&st), sizeof(student));直接从文件中读取student结构数据到 占用的内存中st。
强制转换是因为read需要 a char*,这就是将一种类型的指针转换为完全不相关类型的指针的方式。
此类代码仅在以二进制模式写入和读取文件时才有效,更不用说您几乎必须创建文件并在同一台机器上读取它才能确定它会按预期工作。
即使如此,如果该结构包含指针,它很可能注定会失败。
(-1)*static_cast<int>(sizeof(st));将运算符的无符号结果转换sizeof为有符号数,并将其乘以-1。
上面几行的特点是所谓的c++风格的强制转换。使用它们的原因是,与c风格的强制转换不同,它们不会不惜一切代价执行强制转换。只有满足施法条件才会施法,这样比较安全。
因此,将 unsigned 转换为有符号只需要 a static_cast,如果编译器静态类型检查不成立,则会失败。
reinterpret_cast是一个更强大的野兽(当你想稍微忽略类型系统时这是必需的),但与 c 风格的强制转换相比仍然有一些保护措施。