分享

面试中你不可回避的C、C++的问题(三)

 Null872 2014-12-19

本节继续上一次的关于sizeof的讲解:

这次主要是探讨一下,关于sizeof对于类以及对象之间的内存的大小的关系

二维指针域数组的关系

  1. #include <stdio.h>  
  2.   
  3. int main()  
  4. {  
  5.     //存储的是指针所以是3*4*4=48  
  6.     int ** a[3][4];  
  7.     printf("%d\n",sizeof(a));//48  
  8.     char** b[3][4];  
  9.     printf("%d\n",sizeof(b));//48  
  10.     return 0;  
  11. }  
空类的大小,以及带有虚函数的空类的大小

  1. #include <stdio.h>  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6. class A  
  7. {  
  8. };  
  9.   
  10. class B  
  11. {  
  12. public:  
  13.     virtual void f() {}  
  14. };  
  15.   
  16. int main()  
  17. {  
  18.     A a;  
  19.     cout << sizeof(a) << endl;//1  
  20.     B b;  
  21.     cout << sizeof(b) << endl;//4  
  22.     return 0;  
  23. }  
再来讨论一下,带有类的成员函数以及继承类对象的大小

  1. #include <stdio.h>  
  2. #include <iostream>  
  3. #include <complex>  
  4.   
  5. using namespace std;  
  6.   
  7. class Base  
  8. {  
  9. public:  
  10.     Base() { cout << "Base Constructor !" << endl; }  
  11.     ~Base() { cout << "Base Destructor !" << endl; }  
  12.     virtual void f(int ) { cout << "Base::f(int)" << endl; }  
  13.     virtual void f(double) { cout << "Base::f(double)" << endl; }  
  14.     virtual void g(int i=10) { cout << "Base::g()" << i << endl; }  
  15.     void g2(int i=10) { cout << "Base::g2()" << i << endl; }  
  16. };  
  17.   
  18. class Derived:public Base  
  19. {  
  20. public:  
  21.     Derived() { cout << "Derived Constructor !" << endl; }  
  22.     ~Derived() { cout << "Derived Destructor !" << endl; }  
  23.     void f(complex<double>) { cout << "Derived::f(complex)" << endl; }  
  24.     virtual void g(int i=20) { cout << "Derived::g()" << i << endl; }  
  25. };  
  26.   
  27. int main()  
  28. {  
  29.     Base c;  
  30.     Derived d;  
  31.     Base* pb = new Derived;  
  32.     cout << sizeof(Base) << endl;//4  
  33.     cout << sizeof(Derived) << endl;//4  
  34.     cout << sizeof(pb) << endl;//4  
  35.     cout << sizeof(c) << endl;//4  
  36.     cout << sizeof(d) << endl;//4  
  37.     return 0;  
  38. }  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多