reinterpret_cast< char *>(& st)和(-1)* static_cast< int>会做什么?意思是? [英] What does reinterpret_cast<char *>(&st) and (-1)*static_cast<int> mean?

查看:137
本文介绍了reinterpret_cast< char *>(& st)和(-1)* static_cast< int>会做什么?意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code here is being used for creating a Student Report card project. While trying to understand we can not figure out the use of and functions of the below code:

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

推荐答案

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

File.read(reinterpret_cast<char *> (&st), sizeof(student)); Reads the student structure data directly from a file into the memory occupied by st.

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

The cast is because read expects a char*, and this is how you convert a pointer of one type to a pointer of a completely unrelated type.

仅当以二进制方式写入和读取文件时,此类代码才有效,更不用说您拥有来创建文件并在完全相同的机器上读取文件了它将按预期工作.

Such code will only work when the file is written to and read from in binary mode, not to mention you pretty much have to create the file and read it on the exact same machine to be certain it will work as expected.

即使那样,即使结构包含指针,也很可能注定要失败.

Even then, if the structure contains pointers, it's likely doomed to fail.

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

(-1)*static_cast<int>(sizeof(st)); turns the unsigned result of the sizeof operator into a signed number, and multiplies it by -1.

以上各行的特征是样式的演员表.使用这些标记的原因是,与的问题不同样式的演员表,他们不会不惜一切代价进行演员表.他们只有在满足铸造条件的情况下才会铸造,这更加安全.

The lines above feature what is called c++-style casts. The reason for using those, is that unlike a c-style cast, they will not preform a cast at any cost. They will only cast if the conditions for casting are met, which is much safer.

因此,将无符号转换为带符号仅需要一个static_cast,如果编译器的静态类型检查不成立,该操作将失败.

So casting unsigned to signed only requires a static_cast, which will fail if the compilers static type checking doesn't hold.

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

reinterpret_cast is a much more powerful beast (which is required when you want to somewhat ignore the type system), but still has some safeguards compared to a c-style cast.

这篇关于reinterpret_cast&lt; char *&gt;(&amp; st)和(-1)* static_cast&lt; int&gt;会做什么?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆