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++ 继承向下转型
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01