gpt4 book ai didi

c++ - static_cast 和 double 一样吗?

转载 作者:行者123 更新时间:2023-11-28 02:30:04 26 4
gpt4 key购买 nike

我是 C++ 转换的初学者。我需要知道的是 static_cast<double>double可在任何代码中交换?

在下面的代码中,我可以替换 static_cast<double> 吗?与 double ?这要短得多。我会失去任何可读性吗?

a= static_cast<double> ( 3 ) / static_cast<double>( 7 );

static_cast怎么样?其他基本类型,例如 int , char , size_t

根据解释他们一定是一样的。但是有没有异常(exception)的情况呢?

最佳答案

刚刚阅读When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?


C++11 标准草案调用 T(number)功能符号和(T) number类型转换符号。鉴于表达式列表是单个表达式,它们是等价的:

§5.2.3/1 A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4). [...]

(T) number可以调用static_cast ,在这种情况下具有以下行为:

§5.2.9/4 Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.

您可以节省大量的输入,而只需使用 float 文字(类型为 double)。

a = 3.0 / 7.0;

关于c++ - static_cast<double> 和 double 一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com