this指针存在的意义

首先,我们先来看一个Date类:

#include <iostream>
using namespace std;

class Date
{
public:
    void Init(int year, int month, int day)
    {
        _year = year;
        _month = month;
        _day = day;
    }

    void Print()
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }
private:
    int _year;
    int _month;
    int _day;
};

int main()
{
    Date d1;
    d1.Init(2020, 6, 29);
    d1.Print();

    Date d2;
    d2.Init(2020, 6, 29);
    d2.Print();
    return 0;
}

对于上述类,有这样一个问题:
Date类中有 Init 与 Print 两个成员函数,函数体中没有关于不同对象的区分,那当 d1 调用 Init 函数时,该函数是如何知道应该设置 d1 对象,而不是设置 d2 对象呢?
    C++中通过引入 this 指针解决该问题,即:C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有成员变量的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。
    C++中的成员函数参数中不允许显式的写 this 指针,只能在成员函数的内部使用
    this 指针的类型:类类型* const
this指针

#include <iostream>
using namespace std;

class Date
{
public:
    //void Init(Date* this, int year, int month, int day);
    void Init(int year, int month, int day)
    {
        //this->_year = year;
        //this->_month = month;
        //this->_day = day;
        _year = year;
        _month = month;
        _day = day;
    }

    //void Print(Date* this);
    void Print()
    {
        //cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
        cout << _year << "-" << _month << "-" << _day << endl;
    }
private:
    int _year;
    int _month;
    int _day;
};

int main()
{
    Date d1;
    d1.Init(2020, 6, 29); //d1.Init(&d1, 2020, 6, 4);
    d1.Print(); //d1.Print(&d1);

    Date d2;
    d2.Init(2020, 6, 29); //d2.Init(&d2, 2020, 6, 4);
    d2.Print(); //d2.Print(&d2);
    return 0;
}

小问题:

  1. this指针存在哪里?也就是存在进程地址空间的哪个区域?
    存在栈上,因为它是一个形参。(VS下存在ecx寄存器里来传递)
  2. this指针可以为空吗?
    可以为空,在调用函数的时候,如果函数内部没有使用到this指针去访问成员变量;如果函数内部需要用到this指针去访问成员变量,则不能为空。
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值