转换、强制转换和强制类型转换有什么区别?

3

我已经长时间地回顾这个问题,但一直未能找到答案。所以我决定问一下:转换(conversion)、强制类型转换(casting)和弱类型转换(coercion)之间有什么区别呢?对于这方面的知识,我还有些生疏,如果您能提供代码示例就更好了。


2
"我非常感激使用代码示例。" - 用什么语言?您未能为您的问题应用合适的标签。此外,请注意可能没有通用定义这些术语,因此语言标签将非常有帮助。 - Damien_The_Unbeliever
3
“@danielm2402:‘不管是哪种语言都对我有用’”这是不可能的,因为这些话在不同语言中是不同的。而且许多语言根本没有其中一些词语/概念。 - Nicol Bolas
2
这回答了你的问题吗?强制转换和强制类型转换有什么区别? - anastaciu
2
在C++中,术语“强制转换”并不常用。有“隐式转换”和“显式转换”(“类型转换”),而“类型转换”经常被误用于所有转换(尽管“隐式类型转换”是一个自相矛盾的词)。术语在不同的编程语言中是不同的,你需要学习你感兴趣的语言的定义。 - molbdnilo
在我看来这是个好问题,但你需要摆脱错误的前提,即术语定义是语言无关的(参见建议重复的答案之一,以“My personal usages are:”开头)。口语化的语言是一回事,如果你关心定义,你必须承认每种语言都有自己的定义。 - 463035818_is_not_a_number
显示剩余5条评论
1个回答

3
[C++] 转换、强制转换和强制类型转换的区别是什么?
  • 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"
    

2
我经常发现“强制转换”被用作“隐式转换”的同义词。 - Caleth
你为我澄清了很多事情!你能给我举一个JS中强制转换的小例子吗? - danielm2402
1
@danielm2402 添加了一个示例。 - eerorika

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接