class Aide
{函數
public:spa
char a;指針
virtual void print()繼承
{it
cout << "A" << endl;class
}註釋
};tab
class B: public Adi
{
};
class C : public B
{
void print()
{
cout << "C" << endl;
}
};
int main()
{
cout << sizeof(A) << endl;//8
cout << sizeof(B) << endl;//8
cout << sizeof(C) << endl;//8
system("pause");
return 0;
}
註釋:char佔一個字節,而print函數佔四個字節,由於是虛函數,裏面有虛指針,故大小爲四個字節,
考慮字節對齊的話就是8個字節,而B是繼承A的,因此大小也爲8字節,C也是;不妨動手試試!
class A
{
public:
char a;
virtual void print()
{
cout << "A" << endl;
}
};
class B : virtual public A
{
};
class C : virtual public B
{
void print()
{
cout << "C" << endl;
}
};
int main()
{
cout << sizeof(A) << endl;//8
cout << sizeof(B) << endl;//12
cout << sizeof(C) << endl;//16
system("pause");
return 0;
}
而如果虛繼承的話,它在當前的大小上再加上4字節,關鍵體如今虛繼承的「虛(virtual)」這個關鍵字上,它也含有虛指針因此要再加上四字節!能夠敲代碼試一下。