c++中return this和return *this的区别

this是指向自身对象的指针,*this是自身对象。

也就是说return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆, 若返回类型为A&, 则是本身 )。

return this返回当前对象的地址(指向当前对象的指针)

下面代码写在CPerson类中

CPerson* getCperson()
 	{
		cout<<"返回指向当前对象的指针: "<<this<<endl; 
		return this;
	}
	CPerson getCopy() 
	{
		cout<<"返回当前对象的克隆,当前对象地址为: "<<this<<endl; 
		return *this;
	}
	CPerson & getSelf()
	{
		cout<<"返回当前对象本身: "<<this<<endl; 
		return *this;	
	} 

以下代码写在main函数中

cout<<"p4的地址"<<&p4<<endl;
cout<<"通过getCperson获得当前对象的地址"<<p4.getCperson()<<endl;//返回当前对象的地址(指针) 
cout<<"p4克隆对象的地址"<<&p4.getCopy()<<endl;//返回当前对象的拷贝 
cout<<"p4本身地址"<<&p4.getSelf()<<endl;//返回当前对象本身 

运行效果

在这里插入图片描述

原文地址:https://www.cnblogs.com/PythonFCG/p/13860137.html