What does reinterpret_cast<char *>(&st) and (-1)*static_cast<int> mean?

扶醉桌前 提交于 2019-12-26 03:13:42

问题


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

回答1:


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

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)); 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.

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

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.




回答2:


you can use the method that i had used if you are not able to understand what is File.read(reinterpret_cast<char *> (&st), sizeof(student)); and, int pos=(-1)*static_cast<int>(sizeof(st)); doing and want to understand the code right now....

来源:https://stackoverflow.com/questions/41319180/what-does-reinterpret-castchar-st-and-1static-castint-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!