我已经长时间地回顾这个问题,但一直未能找到答案。所以我决定问一下:转换(conversion)、强制类型转换(casting)和弱类型转换(coercion)之间有什么区别呢?对于这方面的知识,我还有些生疏,如果您能提供代码示例就更好了。
我已经长时间地回顾这个问题,但一直未能找到答案。所以我决定问一下:转换(conversion)、强制类型转换(casting)和弱类型转换(coercion)之间有什么区别呢?对于这方面的知识,我还有些生疏,如果您能提供代码示例就更好了。
Conversion is the creation of a value from an expression, potentially changing the type of the resulting value.
A cast is an explicit way to convert a value. Some conversions do not require a cast. Those are called implicit conversions. Example of an implicit conversion:
int a = 42;
long b = a; // type of expression a is int,
// but implicitly converted to long
Same example using a cast to make the conversion explicit:
long b = static_cast<long>(a);
Type "coercion" is colloquially used as a synonym of conversion, but the term is not used in the specification of the C++ language. The term is used for example in the ECMAScript language (i.e. JavaScript). Example of a coercion in JS:
Number("42") + 42 // == 84
"42" + 42 // == "4242"