Why use static_cast(x) instead of (int)x?

前端 未结 9 1881
滥情空心
滥情空心 2020-11-22 02:38

I\'ve heard that the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?

9条回答
  •  时光取名叫无心
    2020-11-22 03:00

    C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.

    reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.

    static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.

    dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.

    There are a couple of others but these are the main ones you will come across.

提交回复
热议问题