【发布时间】:2018-05-30 20:16:12
【问题描述】:
我的老师在我们的一个选角示例中加入了以下几行。 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"
【问题讨论】:
-
Casting base to derived is UB,这就是你使用虚拟方法的原因。但这不是这里的情况,这是派生到基础的。
-
@PatrickRoberts 将基转换为使用此语法派生的格式不正确(即
(Derived)b或static_cast<Derived>(b)给出错误)
标签: c++ inheritance casting static-cast