return *this和return this有什么区别

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

return this返回当前对象的地址(指向当前对象的指针)。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

猜你喜欢

转载自blog.csdn.net/wangtingze123/article/details/82896148