Multiple inheritance casting from base class to different derived class(从基类到不同派生类的多重继承转换)
问题描述
假设有这样的类层次结构:
Let's assume there is such class hierarchy:
class A //base class
class B //interface
class C : public A, public B
然后创建C对象:
A *object = new C();
是否可以将对象强制转换为 B ?
Is it possible to cast object to B ?
重要提示:我假设我不知道对象是 C.我只知道它实现了接口 B
Important: I assume I don't know that object is C. I just know that it implements interface B
推荐答案
否.这是不可能的(从 A* 直接转换到 B*).
No. This is not possible (direct casting from A* to B*).
因为A和B的地址在class C的不同位置.所以演员表总是不安全的,你可能会遇到意外行为.演示.
Because the address of A and B are at different locations in class C. So the cast will be always unsafe and possibly you might land up in unexpected behavior. Demo.
转换应该总是通过class C.例如
The casting should always go through class C. e.g.
A* pa = new C();
B* pb = static_cast<C*>(pa);
^^^^ go through class C
演示
这篇关于从基类到不同派生类的多重继承转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从基类到不同派生类的多重继承转换
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
