Geekband 作业

1.分别给出下面的类型Fruit和Apple的类型大小(即对象size),并通过画出二者对象模型图以及你的测试来解释该size的构成原因。

class Fruit{test
   int no;
   double weight;
   char key;
public:
   void print() {   }
   virtual void process(){   }
};
   
class Apple: public Fruit{
   int size;
   char type;
public:
   void save() {   }
   virtual void process(){   }
};

一定要考虑的因素:

每个人的编译环境不同,可能结果不同,(注:主要分析编译器为 32bit 的情况);
数据项是从某个数量字节(8,16等)的倍数开始存放

对象模型图:

对象模型图

代码:

Fruit.h

#ifndef  __FRUIT__
#define  __FRUIT__


class Fruit
{
    int no;
    double weight;
    char key;
    
  public:   
    void print() {}
    virtual void process()  {}
    
};


#endif

Apple.h

#ifndef  __APPLE__
#define  __APPLE__


class Apple : public Fruit
{
    int size;
    char type;
//  char type2;
//  char type3;
//  char type4;
//  char type5;
//  char type6;
//  char type7;
//  char type8;

    
  public:
    void save() {}
    virtual void process()  {}
    
};


#endif

test_size.cpp

#include "Fruit.h"
#include "Apple.h"
#include <iostream>
using namespace std;

int main()
{
    Fruit f1;
    Apple a1;
    
    cout << "Fruit的对象f1的size是: " << sizeof(f1) << endl;
    cout << "Apple的对象a1的size是: " << sizeof(a1) << endl;
    
    return 0;
}

结果:

64bit测试结果
64bit调试
32bit测试结果
32bit调试

分析(32bit的情况):

  • 在父类f1中,int no - 4, double weight - 8, char key -1, vptr - 4(通过把其他都注释掉,输出其sizeof得到结果) 超过16,小于24,最终补成24. 因为当我把 char key 注释掉时,结果为16.
#ifndef  __FRUIT__
#define  __FRUIT__


class Fruit
{
    int no;
    double weight;
//  char key;
    
  public:   
    void print() {}
    virtual void process()  {}
    
};


#endif
注释掉char的结果
  • 在子类a1中,除了继承自父类的数据外,又添加了 int size -4, char type - 1 数据
  • 先看上图,注释掉父类中的char ,子类对象size是24,因为父类16 + 子类新添加的 5 < 24, 所以结果为24,。
  • 恢复父类原状,分别修改子类,看看不同结果
#ifndef  __APPLE__
#define  __APPLE__


class Apple : public Fruit
{
//  int size;
   char type;
//  char type2;
//  char type3;
//  char type4;
//  char type5;
//  char type6;
//  char type7;
//  char type8;

   
 public:
   void save() {}
   virtual void process()  {}
   
};


#endif
注释掉int的结果
#ifndef  __APPLE__
#define  __APPLE__


class Apple : public Fruit
{
//  int size;
    char type;
    char type2;
    char type3;
    char type4;
    char type5;
    char type6;
    char type7;
//  char type8;

    
  public:
    void save() {}
    virtual void process()  {}
    
};


#endif
添加几个char后的结果

注:再多添加一个char,结果就变为32了

  • 但在原子类中,只有一个int ,一个char 就使得结果变为32, 可能与编译器要满足内存内部对齐等有关。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容