C ++の継承(6)オブジェクトのサイズクラスで---ダイヤモンド継承

オブジェクトサイズクラスのダイヤモンドの継承

サイズは、空のクラスである1
class A
{

};

int main()
{
	cout << sizeof(A) << endl;
}

ここに画像を挿入説明

処理していない場合には、クラスのサイズを継承

ここに画像を挿入説明

class A
{
protected:
	int _a;
};

class B : public A
{
protected:
	int _b;
};

class C : public A
{
protected:
	int _C;
};

class D : public B, public C
{
protected:
	int _d;
};

int main()
{
	cout << sizeof(A) << endl;
	cout << sizeof(B) << endl;
	cout << sizeof(C) << endl;
	cout << sizeof(D) << endl;
}

ここに画像を挿入説明

クラスDのオブジェクトサイズを計算します

:上記のように、2つのD継承クラスAのメンバーとはint型の5員あるBように、重畳されていない
ここに画像を挿入説明
ため、D級のサイズは20バイトであるが。

Dの場合のクラスサイズは、仮想継承を計算します

ここに画像を挿入説明

class A //基类
{
protected:
	int _a1 = 1;
	int _a2 = 10;
};

class B : virtual public A //B继承A
{
protected:
	int _b = 2;
};

class C : virtual public  A //C继承A
{
protected:
	int _c = 3;
};

class D : public B, public C //D继承B、C
{
protected:
	int _d = 4;
};

int main()
{
	cout << sizeof(A) << endl; //8
	cout << sizeof(B) << endl; //16
	cout << sizeof(C) << endl; //16
	cout << sizeof(D) << endl; //28
}

ここに画像を挿入説明
(D)では、私たちは学んだ次のように、仮想継承クラスオブジェクトモデルを:
ここに画像を挿入説明
、繰り返しAクラス変数の冗長性を防ぐために、知っている仮想ベーステーブルを与えるアクセスに_vbptr仮想ベース・テーブル・ポインタを使用してオフセット方法は、クラスAのメンバーにアクセスすることができます。

サイズクラスのオブジェクトモデルB

そこで、本実施の形態の仮想継承では、クラス・オブジェクト・モデル・クラスBは:
ここに画像を挿入説明
したがって、Bが誘導されるサイズが16バイトです。同様にC.由来

Dサイズのオブジェクトモデル

ここに画像を挿入説明
図から分かるように、Dオブジェクトは二つのポインタ、データ5、及び排除冗長データクラスAの連続を含んでいます。したがって、クラスDのサイズは28バイトです。

公開された52元の記事 ウォン称賛26 ビュー3412

おすすめ

転載: blog.csdn.net/weixin_43796685/article/details/103599466