C++:不能 static_cast 从 double* 到 int*

标签 c++ casting static-cast

当我尝试使用 static_cast 将 double* 强制转换为 int* 时,我收到以下错误:

invalid static_cast from type ‘double*’ to type ‘int*’

代码如下:

#include <iostream>
int main()
{
        double* p = new double(2);
        int* r;

        r=static_cast<int*>(p);

        std::cout << *r << std::endl;
}

我知道在 double 和 int 之间转换会有问题,但为什么在 double* 和 int* 之间转换会出现问题?

最佳答案

您应该使用 reinterpret_cast 来转换指针,即

r = reinterpret_cast<int*>(p);

当然这是没有意义的,

除非你想以 int 级别查看 double!你会得到一些奇怪的输出,我认为这不是你想要的。如果要将 p 指向的 value 转换为 int 那么,

*r = static_cast<int>(*p);

此外,r分配,因此您可以执行以下操作之一:

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

或者

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

关于C++:不能 static_cast 从 double* 到 int*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2473628/

相关文章:

c++ - 错误 : cast from 'Foo*' to 'unsigned int' loses precision

C++ static_cast - 更安全的方式。为什么?

c++ - 从基类转换到派生类抛出异常

c++ - 计时: How can I calculate a millsecond duration from two high resolution time points?

c++ - 递归:将字符串中的 e 换成 a

c++ - 查找函数的所有局部最大值

c# - 泛型类型的转换无效

c++ - char* 和 unsigned char* 不兼容?

c++ - 在将 void* 转换为任何内容时,我应该使用 static_cast 还是 reinterpret_cast

C++ 类继承段错误