当我尝试使用 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/