2016-12-25 141 views
-1

此处的代码正在用于创建学生报告卡项目。在试图理解我们想不通的使用和功能如下代码:reinterpret_cast <char *>(&st)和(-1)* static_cast <int>是什么意思?

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

什么是学生?该代码将其读为原始二进制文件。如果学生类型不是标准布局,则为UB。它也有问题 – Danh

+0

你问你的问题的方式表明你不明白'reinterpret_cast'和'static_cast'是什么。 – Omnifarious

回答

2

File.read(reinterpret_cast<char *> (&st), sizeof(student));直接从一个文件分割成st占用的内存读取student结构的数据。

演员阵容是因为read预计char*,这是如何将一种类型的指针转​​换为完全不相关类型的指针。当文件被写入和二进制模式读取

这样的代码只会工作,更何况你几乎创建文件和读取它的确切同一台机器上是一定会努力为预期。即使如此,如果结构包含指针,它可能注定会失败。


(-1)*static_cast<int>(sizeof(st));转动sizeof操作成有符号数的无符号结果,并通过-1相乘。


上面的代码具有所谓的风格的演员阵容。使用这些的原因是,与类型的演员不同,他们不会不惜一切代价演绎演员。只有满足铸造条件时才会施放,这样更安全。

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

reinterpret_cast是一个非常强大的野兽(当你想要略微忽略类型系统时需要这个野兽),但与c风格演员相比仍然有一些保护措施。

相关问题