this指针是允许依靠返回该类对象的引用值来连续调用该类的成员函数

#include<iostream>
using namespace std;
class date
{
	int year;
	int month;
	public:
	date()
	{
		year=0;
		month=0;
	}
	date& setyear(int yr)
	{
		year=(yr<=2008)?yr:0;
		return *this;
	}
	date& setmonth(int mn)
	{
		month=(mn>0&&mn<=12)?mn:0;
		return *this;
	}
	void print_date() const;
};
void date::print_date() const
{
	cout<<year<<"年"<<month<<"月"<<endl; 
}
int main()
{
	date obj;
	cout<<"We have got:";
	obj.setyear(2008).setmonth(10).print_date();
	obj.print_date();
}


We have got:2008年10月
2008年10月

在以上程序中的三个成员函数setHour(), setMinute( )和setSecond()中都使用语句return *this;,将this所指向的对象t返回给主函数。由于园点运算符(.)的结合率为从左向右,因此表达式obj.setmonth( 10 )的运行结果是返回obj,主程序最后语句顺序地执行了四条语句:

obj.setyear(2008).

setmonth(10)

.print_date();

这体现了连续调用的特点。

date& setyear(int yr)和 date& setmonth(int mn)返回值是对象的引用,调用函数只是复制地址,并不复制对象,也不产生新的临时对象,主函数调用和修改只是同一个对象。
#include<iostream>
using namespace std;
class date
{
	int year;
	int month;
	public:
	date()
	{
		year=0;
		month=0;
	}
	date setyear(int yr)
	{
		year=(yr<=2008)?yr:0;
		return *this;
	}
	date setmonth(int mn)
	{
		month=(mn>0&&mn<=12)?mn:0;
		return *this;
	}
	void print_date() const;
};
void date::print_date() const
{
	cout<<year<<"年"<<month<<"月"<<endl; 
}
int main()
{
	date obj;
	cout<<"We have got:";
	obj.setyear(2008).setmonth(10).print_date();
	obj.print_date();
}
We have got:2008年10月
2008年0月


--------------------------------
Process exited after 5.394 seconds with return value 0
请按任意键继续. . .

date  setyear(int yr)和 date setmonth(int mn)返回值是对象,每次都要建立新的对象。

this指针不在指向单一的对象,而是指向不同的对象。

猜你喜欢

转载自blog.csdn.net/w3071206219/article/details/52724482