cpp中sizeof与指针
一直不清楚c++的sizeof,现在通过实验得到了一些了解。
1 #include<iostream> 2 3 using namespace std; 4 5 class A{ 6 private: 7 char * a1; 8 // ! static int totalPeople=0; //error: ISO C++ forbids in-class initialization of non-const static member 'People::totalPeople'| 9 public : 10 A(){ 11 a1 = (char *)new string ("None"); 12 } 13 }; 14 class B{ 15 private: 16 char * b1 ; 17 int b2 = 2; 18 }; 19 class C:public A, B{ 20 }; 21 void print_boundary(){ 22 int screenLength = 80 ; 23 char dec = '-'; 24 int i = 0; 25 for(;i<screenLength;i++) 26 { 27 cout<<dec; 28 } 29 cout<<flush; 30 } 31 template <typename T> 32 void print_pointer_info( T * p ){ 33 cout<<"sizeof pointer:"<<sizeof(p)<<endl; 34 cout<<"sizeof what point to:"<<sizeof( *p)<<endl; 35 } 36 int main(){ 37 print_boundary(); 38 void * p = NULL; 39 A * a = new A(); 40 B * b = new B(); 41 C * c = new C(); 42 cout<<sizeof(p)<<endl; 43 cout<<sizeof(&p)<<endl; 44 print_pointer_info<A>( a); 45 print_pointer_info<B>( b); 46 print_pointer_info<C>( c); 47 48 } 49 50 /* 51 52 */
运行的结果:
-------------------------------------------------------------------------------- 4 4 sizeof pointer:4 sizeof what point to:4 sizeof pointer:4 sizeof what point to:8 sizeof pointer:4 sizeof what point to:12
总结:
1.对于32位的系统,指针的大小总是32位。
2.sizeof(&p)能够取得所指对象的大小,比如指针指向的是一个类的对象,那么该对象的大小仅仅是其包含的数据的大小,与有多少个函数无关。