C++ 的this指针

this指针用于类的非静态成员函数在访问非静态成员变量时由编译器自动加入的一个参数,this是指向调用函数的对象的指针。

怎么理解呢?

首先,this只能是一个类的对象在需要访问自己的成员变量时调用成员函数,这时候编译器会为函数自动加入一个名字叫做this的参数,类型为【类名的指针】

举例:

#include<iostream>
using namespace std;

class Date  
{
public:
	Date():_year(1970),_month(1),_day(1){}
	Date(int y, int m, int d) :_year(y), _month(m), _day(d){}
	Date(int y) :_year(y)
	{
		_month = 1;
		_day = 1;
	}
	//拷贝构造函数
	Date(const Date & d) :_year(d._year),_month(d._month),_day(d._day){}
	void Display()
	{
		cout << _year << "年" << _month << "月" << _day << "日" << endl;
	}
	~Date()
	{
		cout << "析构函数!" << endl;
	}
	/*bool operator==(const Date& d)
	{
		return this->_year == d._year&&this->_month == d._month&&this->_day == d._day;
	}*/
	friend bool operator==(const Date &d1, const Date &d2);
	
private:
	int _year;
	int _month;
	int _day;
};

bool operator==(const Date &d1, const Date &d2)
{
	return (d1._year == d2._year) && (d1._month == d2._month) && (d1._day == d2._day);
}

int main()
{
	Date d1(2015);
	d1.Display();
	system("pause");
	return 0;
}
当使用d1.Display()函数时,看起开Display()函数没有参数,实际上却是有一个隐藏的this指针的参数,这个this指针的值实际上就是&d1(d1的地址值)

但是,我们不能显式的加上this指针这个参数,必须由编译器自动产生,人为定义编译器会出错。


这也就解释了为什么成员函数中可以直接使用类的私有成员变量,就是因为加了this指针的作用。实际上是通过了this指针的访问。

例如:

	void Display()
	{
		cout << _year << "年" << _month << "月" << _day << "日" << endl;
	}
实际上写 _year编译器会将它变成 this->_year来操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值