在C ++中,static_cast< double>(a)和double(a)之间有什么区别? [英] In C++, what are the differences between static_cast<double>(a) and double(a)?

查看:392
本文介绍了在C ++中,static_cast< double>(a)和double(a)之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a;
// a gets some value
double pi = static_cast<double>(a)/3;

int a;
// a gets some value
double pi = double(a)/3;

你见过后者吗?在我看来,我在Stroustrup写的一些片段中看到它,但我找不到参考。

Have you ever seen the latter? It seems to me I saw it in some snippet written by Stroustrup but I can't find the reference.

推荐答案

认为他们正在建造而不是铸造。考虑:

Someone may have thought they were constructing rather than casting. Consider:

some_fun(std::string("Hello"));

许多人认为他们正在调用构造函数,而实际上他们正在做C型投。它只是这样发生,铸造将看看目标类型的构造函数在其他东西的外观看起来,因此在这里它最终结束了调用构造函数。

Many people think they're calling a constructor there when in fact they're doing a C-style cast. It just so happens that casting will look at constructors of the target type among the long list of other things it looks at and so here it eventually ends up invoking the constructor.


  • 无意中丢弃了constness
  • $ b $
  • Can inadvertently cast away constness
  • Can silently turn into a reinterpret cast
  • Are hard to differentiate with grepping tools.

除此之外,您在两种情况下都执行完全相同的操作。

Besides all that though, you're performing exactly the same operation in both cases.

这篇关于在C ++中,static_cast&lt; double&gt;(a)和double(a)之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆