问题描述
当我尝试使用static_cast将double *转换为int *时,会出现以下错误:
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*’
p>
Here is the code:
#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 *之间转换有问题?
I understand that there would be problems converting between a double and an int, but why is there a problem converting between a double* and an int*?
推荐答案
除了指针, double *
和 int *
没有什么共同之处。你可以对任何不同结构的 Foo *
和 Bar *
指针类型说同样的话。
Aside from being pointers, double*
and int*
have nothing in common. You could say the same thing for Foo*
and Bar*
pointer types to any dissimilar structures.
static_cast
意味着源类型的指针可以被使用作为目标类型的指针,这需要一个子类型关系。
static_cast
means that a pointer of the source type can be used as a pointer of the destination type, which requires a subtype relationship.
这篇关于C ++:不能static_cast从double *到int *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!