Difference between static_cast and (char*)

后端 未结 5 1817
天命终不由人
天命终不由人 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:20

    static_cast is a safer cast than the implicit C style cast. If you try to cast an entity which is not compatible to another, then static_cast gives you an compilation time error unlike the implicit c-style cast.

    static_cast gives you an error here because what you are trying to say is take an int and try to fit it in a char, which is not possible. int needs more memory than what char occupies and the conversion cannot be done in a safe manner.

    If you still want to acheive this,You can use reinterpret_cast, It allows you to typecast two completely different data types, but it is not safe.
    The only guarantee you get with reinterpret_cast is that if you cast the result back to the original type, you will get the same value, But no other safety guarantees.

提交回复
热议问题