C++ inheritance downcasting(C++ 继承向下转型)
问题描述
我的基类如下:
class point //concrete class
{
... //implementation
}
class subpoint : public point //concrete class
{
... //implementation
}
如何从点对象转换为子点对象?我已经尝试了以下所有三个:
How do I cast from a point object to a subpoint object? I have tried all three of the following:
point a;
subpoint* b = dynamic_cast<subpoint*>(&a);
subpoint* b = (subpoint*)a;
subpoint b = (subpoint)a;
这些演员表有什么问题?
What is wrong with these casts?
推荐答案
如何从点对象转换为子点对象?
How do I cast from a point object to a subpoint object?
你不能;除非 point
有一个转换操作符,或者 subpoint
有一个转换构造函数,在这种情况下,对象类型可以在不需要强制转换的情况下进行转换.
You can't; unless either point
has a conversion operator, or subpoint
has a conversion constructor, in which case the object types can be converted with no need for a cast.
您可以从 point
reference(或指针)转换为 subpoint
reference(或指针), 如果引用的对象实际上是 subpoint
类型:
You could cast from a point
reference (or pointer) to a subpoint
reference (or pointer), if the referred object were actually of type subpoint
:
subpoint s;
point & a = s;
subpoint & b1 = static_cast<subpoint&>(a);
subpoint & b2 = dynamic_cast<subpoint&>(a);
第一个 (static_cast
) 更危险;没有检查转换是否有效,因此如果 a
不引用 subpoint
,则使用 b1
将具有未定义的行为.
The first (static_cast
) is more dangerous; there is no check that the conversion is valid, so if a
doesn't refer to a subpoint
, then using b1
will have undefined behaviour.
第二个 (dynamic_cast
) 更安全,但只有在 point
是多态的(也就是说,如果它有一个虚函数)时才有效.如果 a
引用了一个不兼容类型的对象,那么它会抛出异常.
The second (dynamic_cast
) is safer, but will only work if point
is polymorphic (that is, if it has a virtual function). If a
refers to an object of incompatible type, then it will throw an exception.
这篇关于C++ 继承向下转型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 继承向下转型
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01