オブジェクトサイズクラスのダイヤモンドの継承
サイズは、空のクラスである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バイトです。