开发者

What is the best way to cast in C++? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or 开发者_C百科rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

What is the best way to cast from complex to int in C++?


It's difficult to answer your question since there isn't, in general, a way to do this. Mathematically speaking, what does it mean to cast a complex number (a + bi) to a real number (a + 0i)? You could drop the complex term, or restrict yourself to the case where b = 0, I suppose; this first option seems inelegant and the second option doesn't always work.

The second problem you'll have to address is that in C++ the complex template exists for float, double, and long double, none of which have lossless conversions to int. So I suppose that if you work out the details of the first part, you'd then have to ensure that the rest of the cast is still valid.

If what you want to do is extract the real component from a complex, you can do this:

complex<double> myComplex = /* ... */
double real = myComplex.real();

and then possibly

int realInt = static_cast<int>(real);


You can overload operator int ();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜