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

前端 未结 5 2042
梦如初夏
梦如初夏 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:27

    Because you used double * instead of double

    The * after it means that you are declaring a pointer, which is vastly different from a regular double.

    C++ can not safely static_cast a pointer to a different type of pointer like that.

    If you are wanting to do this kinda thing, you must first dereference the variable.

    r=new int(static_cast(*p));
    

    You must use new because a double and an integer can not reside in the same memory space(sanely)

提交回复
热议问题