【发布时间】:2020-05-22 20:23:03
【问题描述】:
考虑这些将充当基类的类:
struct Base1 {
int b1;
void print_Base1_addr() const { std::cout << this << '\n'; }
};
struct Base2 {
int b2;
void print_Base2_addr() const { std::cout << this << '\n'; }
};
如果Derived继承自Base1和Base2:
struct Derived: Base1, Base2 {
int i;
void print_addr() const { std::cout << this << '\n'; }
};
然后此代码在Derived 和Base1 中为this 打印相同的地址,但在Base2 中却没有:
Derived d{};
d.print_addr();
d.print_Base1_addr();
d.print_Base2_addr();
我不明白为什么Derived 中的this 与Base1 中的地址相同。这些不是空类,因为它们都包含一个数据成员(数据成员b1 和i 的地址不同)。好像Base1 与Derived 重叠。
我忽略了什么?
【问题讨论】:
-
值相同,但类型不同。
-
Derived布局大致是[Base1 Base2 i](而不是[i Base1 Base2])。 -
另一个想法:
void print_Base1_addr() const { std::cout << this << " " << &b1 << '\n'; }你会注意到成员变量 b1 也与 Base1 对象本身具有相同的地址。
标签: c++ oop inheritance this multiple-inheritance