您的位置:首页 > 其它

《转》return *this和 return this有什么区别?

2018-06-01 20:33 316 查看

 

别跟我说 return *this 表示返回当前对象,return this 表示返回当前对象的地址(指向当前对象的指针)。

正确答案为:return *this 返回的是当前对象的克隆或者本身(若返回类型为A,则是克隆,若返回类型为A&,则是本身)。

      return this 返回当前对象的地址(指向当前对象的指针),下面我们来看看程序:

#include <iostream>
using namespace std;

class A
{
public:
int x;
A* get()
{
return this;
}
};

int main()
{
A a;
a.x = 4;

if(&a == a.get())
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}

return 0;
}

结果为yes。

再看:

#include <iostream>
using namespace std;

class A
{
public:
int x;
A get()
{
return *this; //返回当前对象的拷贝
}
};

int main()
{
A a;
a.x = 4;

if(a.x == a.get().x)
{
cout << a.x << endl;
}
else
{
cout << "no" << endl;
}

if(&a == &a.get())
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}

return 0;
}

结果为:

4    

no  //可见返回的是当前对象的副本

 

最后,如果返回类型是A&,那么return *this 返回的是当前对象本身(也就是其引用),而非副本。

 

转自:https://www.geek-share.com/detail/2606845620.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: