this指針的調整

  咱們先來看一段代碼:ios

 1 #include <iostream>
 2 
 3 using namespace std;
 4 class A 
 5 {
 6 public:
 7     int a;
 8     A( )
 9     {
10         printf("A:A()的this指針是%p\n", this);
11     }
12 
13     void funcA( )
14     {
15         printf("A:funcA()的this指針是%p\n", this);
16     }
17 };
18 
19 class B
20 {
21 public:
22     int b;
23     B( )
24     {
25         printf("B:B()的this指針是%p\n", this);
26     }
27 
28     void funcB( )
29     {
30         printf("B:funcB()的this指針是%p\n", this);
31     }
32 };
33 
34 class C :public A, public B
35 {
36 public:
37     int c;
38     C( )
39     {
40         printf("C:C()的this指針是%p\n", this);
41     }
42     void funcC()
43     {
44         printf("C:funcC()的this指針是%p\n", this);
45     }
46 };
47 
48 int main()
49 {
50     cout << sizeof(A) << endl;
51     cout << sizeof(B) << endl;
52     cout << sizeof(C) << endl;
53     
54     C cobj;
55 
56     cobj.funcA();
57     cobj.funcB();
58     cobj.funcC();
59     return 0;
60 }

運行結果爲:
web

第一個基類子對象A的起始地址是與派生類對象C是重合的。咱們來看一張圖片:ide

  上圖演示了this指針是如何調整的。在派生類的對象中,基類是做爲派生類的子對象存在的,稱爲基類子對象,當派生類只繼承於一個基類時,基類子對象的起始地址是與派生類對象相同的,而當派生類同時繼承於多個基類時(多重繼承,這裏暫時不考慮虛擬繼承)函數

第一個基類子對象的起始地址是與派生類對象重合的,然後續基類子對象的起始地址與派生類對象依次相差前面的基類子對象的長度,好比,D同時派生於A、B、C。D對象的起始地址是0,那麼A子對象的起始地址也是0,B子對象的起始地址是0+sizeof(A),而C對象的起始地址爲0 + sizeof(A) + sizeof(B)。上面的例子C類派生於A,B。C類對象的地址是006FFD4C,那麼A子對象的起始地址和C類對象的起始地址是同樣的爲006FFD4C,B類對象的起始地址爲006FFD4C + sizeof(A) = 006FFD4C + 4 = 006FFD50this

若是咱們把程修改爲以下,輸入結果會怎麼樣呢?spa

 1 #include <iostream>
 2 
 3 using namespace std;
 4 class A 
 5 {
 6 public:
 7     int a;
 8     A( )
 9     {
10         printf("A:A()的this指針是%p\n", this);
11     }
12 
13     void funcA( )
14     {
15         printf("A:funcA()的this指針是%p\n", this);
16     }
17 };
18 
19 class B
20 {
21 public:
22     int b;
23     B( )
24     {
25         printf("B:B()的this指針是%p\n", this);
26     }
27 
28     void funcB( )
29     {
30         printf("B:funcB()的this指針是%p\n", this);
31     }
32 };
33 
34 class C :public A, public B
35 {
36 public:
37     int c;
38     C( )
39     {
40         printf("C:C()的this指針是%p\n", this);
41     }
42     void funcC()
43     {
44         printf("C:funcC()的this指針是%p\n", this);
45     }
46     void funcB()
47     {
48         printf("C:funcB()的this指針是%p\n", this);  //新增長的代碼
49     }
50 };
51 
52 int main()
53 {
54     cout << sizeof(A) << endl;
55     cout << sizeof(B) << endl;
56     cout << sizeof(C) << endl;
57     
58     C cobj;
59 
60     cobj.funcA();
61     cobj.funcB();
62     cobj.funcC();
63     return 0;
64 }

輸出結果爲:
指針

能夠看到,此時三個值都相同了,C類override基類子對象B的funcB函數,此時funB()中的this指針指向C對象的起始地址。code

相關文章
相關標籤/搜索