Title

this与*this的区别(C++)

this与*this的区别

  • return this返回的是当前对象的地址,毕竟this便是指针

  • 而return *this返回的是this指针所指向的对象,根据引用的有无来确定返回的对象是本身的克隆还是本身。

  • 比如

  • 	    类名 get_copyed()
    		{
    			return *this;
    		}
    
  • 返回的是克隆(印刷品、盗版)

  • 再比如

  • 	    类名& get_original()
    		{
    			return *this;
    		}
    
  • 返回的是本身(原稿)

代码

#include<bits/stdc++.h>
using namespace std;
class A
{
	public:
		int x;
		/***得到指针指向的地址***/
		A* get_address()
		{
			return this;
		}
		/***得到复制样本***/ 
		A get_copyed()
		{
			return *this;
		}
		/***得到原稿***/ 
		A& get_original()
		{
			return *this;
		}
		/***析构函数***/
		
};
int main()
{
	A a;
	a.x=333;
	
	/***确认返回的是地址***/
	if(&a==a.get_address())
	{
		cout<<"地址对上了"<<endl<<"`````````"<<endl; 
	 }
	else
	{
		cout<<"地址没对上"<<endl<<"`````````"<<endl; 
	} 
	
	
	/***copy***/
	A reveive_temporary1=a.get_copyed();
	if(&a!=&reveive_temporary1&&a.x==reveive_temporary1.x)
	{
		cout<<"地址没对上,但值拿到了"<<endl<<"`````````"<<endl; 
	 }
	else 
	{
		cout<<"。。。。"<<endl<<"`````````"<<endl; 
	}  
	
	
	/***原稿***/
	//这里也要用一个引用A& reveive_temporary2
	A& reveive_temporary2=a.get_original();
	if(&a==&reveive_temporary2&&a.x==reveive_temporary2.x)
	{
		cout<<"地址对上了,值也拿走了"<<endl<<"`````````"<<endl; 
	 }
	else 
	{
		cout<<"猜想错误"<<endl<<"`````````"<<endl; 
    }
    
    return 0; 
}

其他

ERROR:taking address of temporary

*this的对象构建完后会马上被销毁,是一个暂时的对象

资料

C++中this与*this的区别

posted @ 2021-05-27 16:40  BeautifulWater  阅读(165)  评论(0编辑  收藏  举报