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

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

    You should use reinterpret_cast for casting pointers, i.e.

    r = reinterpret_cast(p);
    

    Of course this makes no sense,

    unless you want take a int-level look at a double! You'll get some weird output and I don't think this is what you intended. If you want to cast the value pointed to by p to an int then,

    *r = static_cast(*p);
    

    Also, r is not allocated so you can do one of the following:

    int *r = new int(0);
    *r = static_cast(*p);
    std::cout << *r << std::endl;
    

    Or

    int r = 0;
    r = static_cast(*p);
    std::cout << r << std::endl;
    

提交回复
热议问题