为什么派生类的大小增加,即使基类成员是私有的! [英] why the size of derived class increased, even though the base class member is private!

查看:130
本文介绍了为什么派生类的大小增加,即使基类成员是私有的!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码

  class A {
private:
int i;
};
class B:public A {
private:
int j;
};

当找到sizeof派生类对象时,我看到 sizeof baseclass + sizeof derived class ...但是根据继承行为,基类的 private 成员不会继承到派生 class right!为什么派生 class 的大小增加了bot的类型!

解决方案

你或者误解 sizeof 或者你误解了C ++对象的布局(在内存中)。



出于性能原因为了避免间接成本),编译器通常使用组合实现Derivation:

  // A 
+ - +
| i |
+ --- +

// B
+ --- + --- +
| A | j |
+ --- + --- +

注意,如果 private B 即使包含它也不能窥视 A >

sizeof 运算符将返回 B 的大小,包括必要的填充(如果有的话)。



如果你想了解更多,我衷心地推荐在C ++对象模型内。虽然编译器依赖,但许多编译器实际上使用相同的基本原理。


I have following code as below

class A {
  private:
    int i;
 };
class B:public A {
 private:
  int j;
 };

when find the sizeof derived class object i see the sizeof baseclass + sizeof derived class...but as per the inheritance behaviour, the private member of base class are not inherited to derived class right!! why the size of derived class has addition of bot the classes!

解决方案

You either misunderstand sizeof or your misunderstand the layout (in memory) of C++ objects.

For performance reason (to avoid the cost of indirection), compilers will often implement Derivation using Composition:

// A
+---+
| i |
+---+

// B
+---+---+
| A | j |
+---+---+

Note that if private, B cannot peek in A even though it contains it.

The sizeof operator will then return the size of B, including the necessary padding (for alignment correction) if any.

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.

这篇关于为什么派生类的大小增加,即使基类成员是私有的!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆