问题
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*’
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;
}
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*?
回答1:
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
means that a pointer of the source type can be used as a pointer of the destination type, which requires a subtype relationship.
回答2:
You should use reinterpret_cast
for casting pointers, i.e.
r = reinterpret_cast<int*>(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<int>(*p);
Also, r
is not allocated so you can do one of the following:
int *r = new int(0);
*r = static_cast<int>(*p);
std::cout << *r << std::endl;
Or
int r = 0;
r = static_cast<int>(*p);
std::cout << r << std::endl;
回答3:
Floating point-to-integer conversion is supported, so int a = static_cast<int>(5.2)
is fine. However, it's a conversion - the underlying data types are completely incompatible. What you're asking is for the runtime to convert a pointer to an 8-byte structure to a pointer to a 4-byte structure, which it can't do in any meaningful way.
That having been said, if you really want to interpret your double as an integer, int* r = reinterpret_cast<int*>(p)
will work fine.
回答4:
You can convert between a double and an int with static_cast<>
, but not between pointers to different types. You can convert any pointer type to or from void *
with static_cast<>
.
The rationale may be that int *
and double *
are often effectively arrays, and the implementation doesn't know how big the array is.
回答5:
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<int>(*p));
You must use new
because a double and an integer can not reside in the same memory space(sanely)
来源:https://stackoverflow.com/questions/2473628/c-cant-static-cast-from-double-to-int