HOME> 转生系统> this与*this的区别(C++)

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

转生系统 2026-06-23 20:25:25

目录this与*this的区别代码其他ERROR:taking address of temporary资料

this与*this的区别

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

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

比如

类名 get_copyed()

{

return *this;

}

返回的是克隆(印刷品、盗版)

再比如

类名& get_original()

{

return *this;

}

返回的是本身(原稿)

代码

#include

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<<"地址对上了"<

}

else

{

cout<<"地址没对上"<

}

/***copy***/

A reveive_temporary1=a.get_copyed();

if(&a!=&reveive_temporary1&&a.x==reveive_temporary1.x)

{

cout<<"地址没对上,但值拿到了"<

}

else

{

cout<<"。。。。"<

}

/***原稿***/

//这里也要用一个引用A& reveive_temporary2

A& reveive_temporary2=a.get_original();

if(&a==&reveive_temporary2&&a.x==reveive_temporary2.x)

{

cout<<"地址对上了,值也拿走了"<

}

else

{

cout<<"猜想错误"<

}

return 0;

}

其他

ERROR:taking address of temporary

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

资料

C++中this与*this的区别

颇为是什么意思?颇为的解释是什么?颇为拼音怎么读
电脑如何录制gif?4 种方法保姆级教学