c++ - 我的老师不像其他人那样进行类型转换。有谁知道他在做什么?

标签 c++ inheritance casting static-cast

我的老师在我们的一个类型转换示例中包含了以下几行。 cCircle 类的对象,它继承自 Point 类。在寻找“我可以将类 Point 的对象转换为类型 Circle 吗?”这个问题的答案时我发现他使用的语法与我访问过的每个网站都不同。这些网站都使用static_castdynamic_cast 语法。他不会在测试中使用 static_cast 和 dynamic_cast,我只是想知道他在使用什么以及它是如何运作的。

此外,如果您对我是否可以将基对象转换为派生类型有任何疑问,我将非常感谢您。

output << "the center of the circle is at " << (Point) c; 
// casting `Circle` object `c` with type `(Point)`, calls the first overloaded >stream insertion operator"

最佳答案

(Point)c 被称为“C 风格”转换。这基本上可以被认为是一种蛮力转换,它会尽其所能使转换成功。这意味着它最终可能导致 static_castconst_cast 甚至 reinterpret_cast

When the C-style cast expression is encountered, the compiler attempts to interpret it as the following cast expressions, in this order:

  • const_cast
  • 静态转换
  • static_cast 后跟 const_cast
  • 重新解释_cast
  • reinterpret_cast 后跟 const_cast

来源:https://en.cppreference.com/w/cpp/language/explicit_cast

来自 Stroustrup 本人:

Explicit type conversions (often called casts to remind you that they are used to prop up something broken) are best avoided.

C-style casts should have been deprecated in favor of named casts.

Stroustrup、Bjarne。 C++ 之旅(C++ 深入系列)(Kindle 位置 7134)。培生教育。 Kindle 版。

因此推荐命名转换。在实践中,我仍然会遇到使用 C 风格转换的专业代码,因为它使代码更加简洁和可读,并且——如果你知道你在做什么——通常等同于 static_cast 在它的地方用过的。对于它的值(value),我认为如果出于这些原因在使它显而易见的上下文中使用 C 样式转换是可以的,它将导致 static_cast,而 Stroustrup 即将到来从过度面向对象的角度来看,他对类型转换普遍不屑一顾。但您应该更喜欢命名转换。

您的老师可能正在使用 C 风格的转换作为一种看起来不那么可怕的转换介绍。

关于c++ - 我的老师不像其他人那样进行类型转换。有谁知道他在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47852346/

相关文章:

mysql - 将字符串转换为 double (非十进制)

c# - 仅添加新方法而不添加数据时使用什么 OOP 模式?

c++ - 为什么空的 unordered_map.find 不返回 end()?

c++ - 指向指针 vector 的指针的内存消耗

java - 类继承 : generic extends generic

c++ - 如何避免特定类方法的 C++ 转换?设计模式?

java - 普通接口(interface)类和只有抽象方法的抽象类有什么区别吗?

c# - 向上类型转换-c#

c++ - 如何返回首字母大写的单词

c++ - boost::accumulator::tag::mean 的返回类型