关于C++中具有多重继承"this"指针的说明

Clarification on "this" pointer with multiple inheritance in C++

本文关键字:this 指针 说明 多重继承 C++ 关于      更新时间:2023-10-16

对于"this"指针如何与基类和派生类一起工作,我有点困惑。考虑这个代码:

class A {
//some code
};

class B:  public A {
//some code
}; 

假设从类B调用的"this"指针将指向与从基类a中的某些代码调用的"this"指针相同的地址,这正确吗?

多重继承呢?

class A {
//some code
};
class B {
//some code
};
class C:  public A, public B {
//some code
}; 

假设从类C调用的"this"指针将指向与从基类a或B中的某些代码调用的"this"指针相同的地址,这正确吗?

假设从类B调用的"this"指针将指向与从基类a中的某些代码调用的"this"指针相同的地址,这正确吗?

不,你不能这么认为。然而,尽管不是必需的,但许多实现将使用相同的地址(用clang 11gcc 10测试(。

对于多重继承,在您的示例中,clang 11gcc 10class C的实例及其基A使用相同的地址。基础B将具有另一个地址。

另一个例子是具有公共基础实例的多重继承:

struct A {};
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {};

D实例化,得到gcc 10clang 11:

D: 0x7ffc164eefd0
B: 0x7ffc164eefd0 and A: 0x7ffc164eefd0 // address of A and B = address of D
C: 0x7ffc164eefd8 and A: 0x7ffc164eefd0 // different address for C

没有规则指定派生类和基类实例的地址之间的关系。这取决于实现。