C++ 菱形继承 的 对象模型01

  1. 先看 普通菱形继承
#include <iostream>
#include <string>
using namespace std;
class Animal {
	int a_age;
};
class Sheep :  public Animal {};
class Tuo :  public Animal {};
class SheepTuo : public Sheep, public Tuo {};
void test1() {
	cout << sizeof(Animal) << endl;  //4
	cout << sizeof(Sheep) << endl;   //4
	cout << sizeof(SheepTuo) << endl; //8
}
int main()
{
	test1();
	return 0;
}

使用vs提供的开发者命令行工具,位置在 C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts, 打开切换到 cpp文件所在目录
cl /d1 reportSingleClassLayout类名 文件名
对象模型如下:
在这里插入图片描述
2 菱形继承 使用了虚继承 virtual 后的对象模型

#include <iostream>
#include <string>
using namespace std;
class Animal {
	int a_age;
};
class Sheep : virtual public Animal {};
class Tuo : virtual public Animal {};
class SheepTuo : public Sheep, public Tuo {};
void test1() {
	cout << sizeof(Animal) << endl;  //4
	cout << sizeof(Sheep) << endl;   //8
	cout << sizeof(SheepTuo) << endl; //12	
}
int main()
{
	test1();
	return 0;
}

在这里插入图片描述

疑惑:

  1. C++ 在64位机器中 , 任何指针 占用的字节数都是四个字节吗?
发布了100 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43903378/article/details/103936679
今日推荐