Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

casting - C++: can't static_cast from double* to 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*’

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*?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...