class A
{
public:
char a;
virtual void print()
{
cout << "A" << endl;
}
};
class B: public A
{
};
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)”这个关键字上,它也含有虚指针所以要再加上四字节!可以敲代码试一下。
转载于:https://blog.51cto.com/xiexiankun/1854357