cpp中sizeof與指針

一直不清楚c++的sizeof,如今經過實驗獲得了一些瞭解。

ios

 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 */

運行的結果:c++

--------------------------------------------------------------------------------
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位。spa

2.sizeof(&p)可以取得所指對象的大小,好比指針指向的是一個類的對象,那麼該對象的大小僅僅是其包含的數據的大小,與有多少個函數無關。指針

相關文章
相關標籤/搜索