- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的老师在我们的一个类型转换示例中包含了以下几行。 c
是 Circle
类的对象,它继承自 Point
类。在寻找“我可以将类 Point
的对象转换为类型 Circle
吗?”这个问题的答案时我发现他使用的语法与我访问过的每个网站都不同。这些网站都使用static_cast
和dynamic_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_cast
和 const_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:
来源: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/
我是一名优秀的程序员,十分优秀!