先不要看結果,看一下你是否真正了解了this指針?
1 #include<iostream> 2 using namespace std; 3 4 class Parent{ 5 public: 6 int x; 7 Parent *p; 8 public: 9 Parent(){} 10 Parent(int x){ 11 this->x=x; 12 p=this; 13 } 14 virtual void f(){ 15 cout<<"Parent::f()"<<endl; 16 } 17 void g(){ 18 cout<<"Parent::g()"<<endl; 19 } 20 21 void h(){ 22 cout<<"Parent::h()"<<endl; 23 f(); 24 g(); 25 y(); 26 cout<<"LOOK HERE: "<<x<<endl; 27 } 28 29 private: 30 void y(){ 31 cout<<"Parent::y()"<<endl; 32 } 33 }; 34 35 class Child : public Parent{ 36 public: 37 int x; 38 39 public: 40 Child(){} 41 Child(int x) : Parent(x+5){//正確的調用父類構造函數要寫在初始化型參列表中 42 43 //這樣企圖調用父類的構造函數是錯誤的,因為這是另外創造了一個臨時對象,函數結束之后就什么都沒有了! 44 //Parent(x+5); 45 this->x=x; 46 } 47 void f(){ 48 cout<<"Child f()"<<endl; 49 } 50 void g(){ 51 cout<<"Child g()"<<endl; 52 } 53 }; 54 55 int main(){ 56 //例一 57 Child *ch=new Child(); 58 ch->h(); 59 cout<<endl; 60 //例二: 61 ch=new Child(5); 62 ch->h(); 63 cout<<endl; 64 65 //例三: 66 ch->p->h(); 67 return 0; 68 }
/* Parent::h() Child f() Parent::g() Parent::y() LOOK HERE: 9306304Parent::h() Child f() Parent::g() Parent::y() LOOK HERE: 10Parent::h() Child f() Parent::g() Parent::y() LOOK HERE: 10 */
?
首先Child繼承了Parent中的 h()方法!
我們new 了一個Child類的對象XXX, 用ch指向了它!
當ch去調用h()方法的時候,好了關鍵的問題來了,那就是此時的this指針到底是指向誰的....
要知道,this指針是和對象相關的,所以無論怎樣,那么調用h()方法的是XXX這個對象,
那么this就是指向XXX這個對象XXX!在入棧的時候,this也一同被壓入!既然this是指向XXX
的,為什么會調用基類的g()方法呢?然后又調用的是派生類中的f()方法呢?(注意:g()方法
和f()方法在基類和派生類中都有).....
仔細看一下,是不是感覺和派生類向上轉型為基類的多態差不多啊。子類在調用h()方法時,其實
默認將this的類型進行了向上提升,也就是由Child* this -> Parent* this;想一想這是必須的,
why?因為h()只是派生類繼承基類的,并沒有進行重寫!如果沒有進行this的類型提升,那么
如果h()方法中存在對基類私有成員的訪問,比如這個子類中的y()方法是私有的!h()中調用了
y(); 也就是this->y();是不是矛盾了?派生類中怎么可以訪問基類中的私有成員呢???
所以this的類型一定向上提升了!
如果還是不信,那你看一下 樣例2 中的x值是不是輸出的是基類中的 x 的值!
再看一看 樣例3中的輸出是不是和樣例2的輸出時一樣的!從f()的調用和g()調用
可以看出是多態的結果...