C++中的this指针

一.this指针的实现
[cpp] view plain copy
 
#include<iostream>  
using  namespace std ;  
<span style="font-family: Arial, Helvetica, sans-serif;">class Date1</span>  
{  
public:  
      
    void InitDate(int year, int month, int day)  
    {  
          
           _year = year;  
        _month = month;  
        _day = day;  
    }  
  
      
  
protected:  
    int _year;  
    int _month;  
    int _day;  
  
};  
  
  
  
int main()  
{  
    Date1 d1, d2, d3;  
    d1.InitDate(2016, 10, 8);  
    d2.InitDate(2016, 10, 7);  
    d3.InitDate(2016, 10, 9)  
cout << "hello..." <<endl;  
system("pause");  
return 0;  
}  
这个程序在我们刚接触C++不久,大家都能写出来,但是我们是否考虑一个这样的问题,类是如何知道对象d1,d2,d3调用成员函数呢?
这也就是我们这篇博客的内容了,类的非静态成员函数都隐藏了一个this指针,这个指针指向所调用的对象。
void InitDate(int year, int month, int day);  函数被改成void InitDate( Date * const this, int year ,int month ,int day);
d1.InitDate(2016,10,8) 在底层的实现是 InitDate(&d1,2016,10,8),
通过这种机制,类能清楚的知道是那个对象调用了类的成员函数。
因为存在this指针,如果类成员变量year和参数重名,我们可以通过this->year = year来操控成员变量

类中的静态成员函数是属于类的,不是属于具体的对象。这个函数中没有隐藏this指针。这个函数可以通过类+域作用符+函数名调用,也可以通过对象去调用。
如果类中有个成员函数static int fun(int a, int b).
d1.fun(1,2) 在 底层实现是fun(1,2)。
二、this经典题目分析
[cpp] view plain copy
 
#include<iostream>  
using  namespace std ;  
  
class CTest  
{  
public:  
    void FunTest()  
    {  
        cout<<this->data<<endl; //程序崩溃。  //空指针去访问数据成员,程序肯定崩溃。  
    }  
  
    int data;  
};  
  
void FunTest()  
{  
    CTest* pt = NULL;  //成员函数被解释成FunTest(CTest * this)  
    pt->FunTest();  //编译通过  这条语句被解释成FunTest(pt)  
}  
  
int main()  
{  
    FunTest();  
    return 0;  
}  

三. 关于this指针的一个精典回答:
当你进入一个房子后,
你可以看见桌子、椅子、地板等,
但是房子你是看不到全貌了。
对于一个类的实例来说,
你可以看到它的成员函数、成员变量,
但是实例本身呢?
this是一个指针,它时时刻刻指向你这个实例本身。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值