对象的继承和大小 [英] Inheritance and size of object

查看:105
本文介绍了对象的继承和大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我假设我的基类有一个int成员,派生类也有一个int成员。现在,当我创建一个派生类对象,并看到sizeof(derivedClassObject)的输出,那么它变成8.现在我很困惑,抓住这里的基本想法。

I'm assuming that my base class has one "int" member and the derived class has also one "int" member. Now when I create one derived class object and see the output by sizeof(derivedClassObject) then it is becoming 8. Now I am troubling to grasp the underlying idea here.

我知道当我为派生类创建一个对象时,基类构造函数和派生类构造函数都会被调用。这里的基类构造函数的唯一目的是初始化基类数据成员。我预计sizeof将显示4,因为我只有兴趣创建一个派生类对象。但是,而不是我得到的输出为8。所以,额外的4字节正在分配,我认为它发生在基类构造函数。如果有人帮助我掌握以下概念,我将不胜感激:

I know that when I create an object for the derived class then both the base class constructor and derived class constructor are get called. The only purpose of base class constructor here is to initialize the base class data members. I expected that the sizeof will display 4 because I am only interested to create a derived class object. But instead of that I am getting output as "8". So, extra 4 byte is being allocated and I think its happening for the base class constructor. I would appreciate if anyone help me to grasp the following concepts:


  • 当我创建一个派生类时,为什么要分配8个字节而不是4目的?这是否意味着基类构造函数也创建一个新的基类对象并将其与新的派生类对象连接?

我只是创建一个派生类对象,派生类对象的大小是:sizeof(baseClassObject)+ sizeof(derivedClassObject) 。

I am just creating one derived class object and the size of that derived class object is: sizeof(baseClassObject) + sizeof(derivedClassObject). I would really appreciate to get some help.

推荐答案

一般来说继承 in oop意味着派生类的对象也是基类的对象。因此,它包含基类包含的所有内容(在这种情况下一个int,所以4字节)和任何额外的数据成员从派生类(所以另一个int)。

In general inheritance in oop means that an object of a derived class is also an object of the base class. Therefore it contains everything the base class contained (in this case one int, so 4 byte) and any additional data members from the derived class (so another int).

如果不是这样,派生类的对象如何作为基类的对象使用?继承的方法可能会做可怕的事情,因为他们试图访问的数据成员不存在。

If that wasn't the case, how would an object of the derived class be usable as an object of the base class? Inherited methods would likely do horrible things, since the data members they are trying to access wouldn't exist.

因此 sizeof(derivedClass)= = sizeof(baseClass)+ sizeof(int)(虽然没有什么是保持编译器使它更大)。

Therefore the sizeof(derivedClass)==sizeof(baseClass) + sizeof(int) (although nothing is keeping the compiler from making it bigger).

如果您不希望您的 derivedClass 可用作 baseClass 你不应该从它派生。

If you don't want your derivedClass to be usable as a baseClass you shouldn't derive from it.

这篇关于对象的继承和大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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