Difference between static_cast and (char*)

后端 未结 5 1781
天命终不由人
天命终不由人 2020-12-20 18:43

this is my first question :)

I have one pile file, and I have open it like shown below ;

ifstream in ( filename,  ios :: binary | ios :: in ) 
         


        
5条回答
  •  礼貌的吻别
    2020-12-20 19:10

    You should have used reinterpret_cast instead of static_cast, because the data types are not related: you can convert between a pointer to a subclass to a superclass for instance, or between int and long, or between void * and any pointer, but unsigned int * to char * isn't "safe" and thus you cannot do it with static_cast.

    The difference is that in C++ you have various types of casts:

    • static_cast which is for "safe" conversions;

    • reinterpret_cast which is for "unsafe" conversions;

    • const_cast which is for removing a const attribute;

    • dynamic_cast which is for downcasting (casting a pointer/reference from a superclass to a subclass).

    The C-style cast (char *)x can mean all of these above, so it is not as clear as the C++ casts. Furthermore, it is easy to grep for a C++-style cast (just grep for _cast), but it's quite hard to search for all C-style casts.

提交回复
热议问题