c++中多继承的实现的时候,编译器会偷偷给虚继承的类增加属性4个字节


#include <iostream>
#include<stdlib.h>
using namespace std;


class B
{
public:
	B()//构造函数
	{
		cout<<"B构造函数执行\n";
	}
	int b;
protected:
private:

};

class B1 : virtual public B //12
{
public:
	int b1;

};

class B2 :    public B //8
{
public:
	int b2;
};

class C : public B1, public B2
{
public:
	int c;
};

void main()
{
	cout<<sizeof(B)<<endl; //4
	cout<<sizeof(B1)<<endl; //12 //加上virtual以后 , C++编译器会在给变量偷偷增加属性
	cout<<sizeof(B2)<<endl;  //8
	//cout<<sizeof(B)<<endl;

	system("pause");

}
/*
在VC++6.0中的结果是:
---------------------------------------------
4
12
8
请按任意键继续. . .


---------------------------------------------
*/

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89205681