原文地址:https://blog.csdn.net/stpeace/article/details/22220777
说说为什么我要再写一篇文章,近些年学习编程的路上,深受各种错误翻译和一些错误理解的干扰,于是希望给后来人能指引一条争确的路,起码不误导他们,所以看到讲的不清楚不对的忍不住要写点东西。
下边是原文:
别跟我说, 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返回的是当前对象本身(也就是其引用), 而非副本。
---------------------
版权声明:本文为CSDN博主「stpeace」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/stpeace/article/details/22220777
下边是我的一些想法:return this;返回的就是当前对象的指针,这个没什么好说的;
但是,当当当,重点来了,return *this;这个返回的究竟是什么呢,声明返回类型时怎么写呢,结论来了,有两种写法
A get()//这样写返回的就是一个拷贝,地址和原来对象地址不一样了
{
return *this;
}
或者
A& get()//这样写返回的就是一个引用,返回的就是原来的对象
{
return *this;
}