C++: can't static_cast from double* to int*

前端 未结 5 2124
梦如初夏
梦如初夏 2020-12-17 10:01

When I try to use a static_cast to cast a double* to an int*, I get the following error:

invalid static_cast from type ‘double*’ to type ‘int*’
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 10:30

    Floating point-to-integer conversion is supported, so int a = static_cast(5.2) is fine. However, it's a conversion - the underlying data types are completely incompatible. What you're asking is for the runtime to convert a pointer to an 8-byte structure to a pointer to a 4-byte structure, which it can't do in any meaningful way.

    That having been said, if you really want to interpret your double as an integer, int* r = reinterpret_cast(p) will work fine.

提交回复
热议问题