一道关于继承类的sizeof大小问题

 
  1. #include <iostream> 
  2. using namespace std; 
  3. struct A{ 
  4.                 virtual int fun(); //4 byte 
  5.                 char x; //1 byte 
  6. }; 
  7. struct B:public A{ 
  8.                 short myfun(); //2 byte  不占类B空间
  9.                 union
  10.                         unsigned short m; 
  11.                         unsigned int c; 
  12.                 }xx; //4 byte 
  13.                 int (__stdcall *funs)(); //4 byte 
  14. }; 
  15. union
  16.     unsigned short m; 
  17.     unsigned int c; 
  18. }xx; 
  19. short myfun(); 
  20. int (__stdcall *funs)(); //4 byte 
  21. struct C{ 
  22.                 short myfun(); //2 byte 
  23.                 union
  24.                         unsigned short m; 
  25.                         unsigned int c; 
  26.                 }xx; //4 byte 
  27.                 int (__stdcall *funs)(); //4 byte 
  28. }; 
  29. int main() 
  30. {
  31. //cout<<endl;
    //cout<<offsetof( B , x )<<endl;
    //cout<<offsetof( B , xx )<<endl;
    //cout<<offsetof( B , funs )<<endl;
  32. cout < < sizeof(myfun()) < < endl;//2 
  33. cout < < sizeof(( *funs)()) < < endl;//4 
  34. cout < < sizeof(xx) < < endl;//4 
  35. cout < < sizeof(A) < < endl;//8 
  36. cout < < sizeof(B) < < endl;//16 
  37. cout < < sizeof(C) < < endl;//8 
  38. return 0; 
  39. //为啥sizeof(B)是16而不是18??offsetof可以看偏移
  40. //看深入探索C++对象模型,类中非虚函数不占空间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值