码迷,mamicode.com
首页 > 编程语言 > 详细

c++中基类与派生类中隐含的this指针的分析

时间:2014-09-09 21:20:19      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   div   问题   sp   

先不要看结果,看一下你是否真正了解了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: 9306304

Parent::h()
Child f()
Parent::g()
Parent::y()
LOOK HERE: 10

Parent::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()调用
可以看出是多态的结果...

c++中基类与派生类中隐含的this指针的分析

标签:style   blog   color   os   io   ar   div   问题   sp   

原文地址:http://www.cnblogs.com/hujunzheng/p/3963320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!