题目说明:
分别给出下面的类型Fruit和Apple的类型大小(即对象size),并通过画出二者对象模型的方式来解释该size的构成原因。
本题所采用的是Win10 x64上的Clion,用C++ 11标准进行编译。
测试代码如下(简书怎么贴代码比较好看@=@,不太会):
#include
#include "fruit.h"
int main() {
std::cout<< "sizeof(Fruit) = " <
std::cout<< "sizeof(Apple) = " <
Fruit fruit;
Apple apple;
std::cout<< "Fruit = " << &fruit <
std::cout<< "Fruit.no = " << &fruit.no <
std::cout<< "Fruit.weight = " << &fruit.weight <
printf("Fruit.key = 0x%x\n",&fruit.key);
//printf("Fruit.print() = 0x%x\n",&fruit.print);
//printf("Fruit.process() = 0x%x\n",&fruit.process);
std::cout<< "Apple = " << &apple <
std::cout<< "Apple.no = " << &apple.no <
std::cout<< "Apple.weight = " << &apple.weight <
//std::cout << "Apple.key = " << &apple.key << std::endl;
printf("Apple.key = 0x%x\n",&apple.key);
std::cout<< "Apple.size = " << &apple.size <
//std::cout << "Apple.type = " << &apple.type << std::endl;
printf("Apple.type = 0x%x\n",&apple.type);
//printf("Apple.print() = 0x%x\n",&apple.print);
//printf("Apple.save() = 0x%x\n",&apple.save);
//printf("Apple.process() = 0x%x\n",&apple.process);
return 0;
}
编译后的输出结果是:
sizeof(Fruit) = 32
sizeof(Apple) = 40
Fruit = 0x61fe30
Fruit.no = 0x61fe38
Fruit.weight = 0x61fe40
Fruit.key = 0x61fe48
Apple = 0x61fe00
Apple.no = 0x61fe08
Apple.weight = 0x61fe10
Apple.key = 0x61fe18
Apple.size = 0x61fe1c
Apple.type = 0x61fe20
借用一张模型图来说话
从编译执行结果来看,Fruit和Apple对象在其成员内存之前都有一个8字节的虚表指针。虚表指向内存中单独的一块区域,在那里存放着这个类的虚函数,当调用时,通过传入this指针,虚函数得知作用的对象从而得到执行。而Apple比Fruit内存空间大了8个bit,是因为Apple除了继承自父类Fruit的数据成员,它自身还有一个类型为char的type成员变量。