假设我们有一个具体类 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 没有超类型,实际上,有许多类似于 C 的类,只有 A 和 B。请随意质疑我的逻辑和这个设计示例,但问题仅与指针对齐有关.