问题描述
我有以下代码:
class A {
private:
int i;
};
class B : public A {
private:
int j;
};
当我检查 sizeof(B)
时,它似乎是 sizeof(base)+ sizeof(派生)
。但是,我对继承的理解是基类的 private
成员不会被继承。那么为什么它们包含在 sizeof(B)
的结果中?
When I check sizeof(B)
, it appears to be sizeof(base) + sizeof(derived)
. However, my understanding of inheritance is that the private
members of a base class are not inherited. Why then are they included in the result of sizeof(B)
?
推荐答案
sizeof 或者你误解了C ++对象的布局(在内存中)。
You either misunderstand sizeof
or your misunderstand the layout (in memory) of C++ objects.
出于性能原因(为了避免间接成本),编译器通常会使用Composition实现Derivation:
For performance reason (to avoid the cost of indirection), compilers will often implement Derivation using Composition:
// A
+---+
| i |
+---+
// B
+---+---+
| A | j |
+---+---+
请注意,如果 private
, B
无法查看 A
,即使它包含它。
Note that if private
, B
cannot peek in A
even though it contains it.
sizeof
运算符将返回 B
的大小,包括必要的填充(用于对齐校正),如果有的话。
The sizeof
operator will then return the size of B
, including the necessary padding (for alignment correction) if any.
如果你想了解更多,我衷心推荐 Stanley A. Lippman 。虽然编译器依赖,但许多编译器实际上使用相同的基本原则。
If you want to learn more, I heartily recommend Inside the C++ Object Model by Stanley A. Lippman. While compiler dependent, many compilers do in fact use the same basic principles.
这篇关于为什么派生类的大小包括基类的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!