假设我们有一个具体类 A 和一个抽象类 B。
考虑一个具体的 C,它继承了 A 和 B,并实现了 B:
class C : public A, public B
{
/* implementation of B and specific stuff that belongs to C */
};
现在我定义了一个函数,它的签名是void foo(B* b);
这是我的代码,我可以假设每个指向 B 的指针都是 A 和 B。 在 foo 的定义中,如何获得指向 A 的指针? 一个讨厌但有效的技巧是像这样对齐反向指针:
void foo(B* b)
{
A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(b) - sizeof(A));
// now I can use all the stuff from A
}
请记住,C 没有父类(super class)型,实际上,有许多类似于 C 的类,它们只有 A 和 B。请随意质疑我的逻辑和这个设计示例,但问题只是关于指针对齐。
最佳答案
void foo(B* b)
{
//A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(b) - sizeof(A)); // undefined behaviour!!!!
A* a = dynamic_cast<A*>(b);
if (a)
{
// now I can use all the stuff from A
}
else
{
// that was something else, not descended from A
}
}
忘了说:为了使工作动态转换,A 和 B 都应该有虚函数或至少有虚析构函数。否则没有合法的方法来进行该类型转换。
关于c++ - 处理多重继承时如何对齐指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5673694/