C++ 中的类型转换

Type-casting in C++

我正在使用这本书学习 C++ 两个月:Programming principles and practice using C++,现在我想澄清一些关于我的铸造的疑惑。当我执行隐式转换时,例如:

char c = 'a'; 
int b = c; 

这里c的值被隐式转换为int类型,没有使用任何显式运算符。这算铸造吗?或者在我必须执行显式转换时才考虑转换,例如:

int a = 10; 
int b = 5.5; 
double sum = double (a) / b; 

我知道这听起来可能是个愚蠢的问题,但我只是想确定一下转化率。

"Casting" 仅当您执行 显式 转换时。

话虽如此,您会发现该术语在整个 Internet 和各种团队中都被滥用!

扩大(保值)转换——其结果在转换回其原始类型时会给出原始值的转换——通常是隐式完成的。这个

char c = 'x'; 
int b = c;

是隐式转换。显式转换称为 casts.

int a = 1;
double sum = static_cast<double>(a) / b;

此处将 a 转换为 double 是明确完成的,因为 ab 都是 int;如果没有转换,就不会发生转换,从而导致整数除法,而浮点除法可能是首选,因为它可能更精确。将 / 的一个操作数转换为 double,这将导致另一个操作数也隐式转换为 double,因此除法(及其结果)现在将是浮点数.

如果您只执行 double x = a;,则可以取消显式转换,因为 int 会隐式转换为 double (live example)。来自C++11标准,N3337草案

— if either operand is double, the other shall be converted to double.

有关执行的隐式转换的完整列表,请参阅 here

这不是强制转换,而是标准转换,如 C++ 标准 n3337 在

中所述

§ 4 Standard conversions

4.5 Integer promotions

1) A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

转换表达式中变量的显式转换。像这样

int a = 10; 
int b = 5.5; 
double sum = double (a) / b; 

而这个

char c = 'a'; 
int b = c;

.. 是隐式类型转换(或有时强制转换)其中数据类型从一种类型隐式提升到另一种类型的示例 [喜欢 char 到 int]

查看 this 文章以获得更多见解。

干杯!

如其他答案中所述,转换是明确编写的。该标准将它们称为显式类型转换; [expr.cast]/2:

An explicit type conversion can be expressed using functional notation (5.2.3), a type conversion operator (dynamic_cast, static_cast, reinterpret_cast, const_cast), or the cast notation.

上面引用中提到的三种表达式,我们称之为强制转换:

  • (T)expr。在标准中,这种形式被称为显式类型转换的 cast notation,通常也被称为 C 风格的 cast(因为它是 C 中使用和继承的语法)。 (double) a 是一个例子。

  • T(expr)。这就是 函数式表示法 (也称为函数式转换)。通常用于创建 class 类型的临时对象,例如std::string("Hello World")double(a) 也是函数式转换。

  • 最后但同样重要的是,所谓的类型转换运算符static_cast<T>(expr),reinterpret_castconst_castdynamic_cast。这些是最明确的表示法,并且单独受到更多限制。

this Q/A.

中涵盖了所有这些的使用

执行的所有其他转换不称为转换。