类的虚函数\虚继承所占的空间
本文地址: http://blog.csdn.net/caroline_wendy/article/details/24236469
char占用一个字节, 但不满足4的倍数时, 会进行数据对齐, 使用4的倍数的字节(byte).
无论是虚函数还是虚继承, 都需要将指针存储在虚函数表(virtual function table), 占用4个字节.
继承会继承基类的数据, 和虚函数表, 即继承基类的空间.
代码:
/* * test.cpp * * Created on: 2014.04.20 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> using namespace std; class A { char k[5]; public: virtual void aa() {}; }; class B : virtual public A { char j[6]; public: virtual void bb() {}; }; class C : virtual public B { char i[7]; public: virtual void cc() {}; }; int main() { std::cout << "sizeof(A) = " << sizeof(A) << std::endl; std::cout << "sizeof(B) = " << sizeof(B) << std::endl; std::cout << "sizeof(C) = " << sizeof(C) << std::endl; return 0; }
输出:
sizeof(A) = 12 sizeof(B) = 24 sizeof(C) = 36