return *this和return this

来源:互联网 发布:可以美化图片的软件 编辑:程序博客网 时间:2024/05/21 09:08

看到书中的return *this比较疑惑,查询过后总结如下。

class temp{    ...;}

假如定义temp *get(){return this;},那么返回的this就是地址,即返回一个指向对象的指针
假如定义temp get(){return *this;} 那么返回的就是对象的克隆,是一个临时变量
假如定义temp &get(){return *this;} 那么返回的就是对象本身

例如:

#include<iostream>using namespace std;class A{    public:    int x;    A get()    {        return *this;    }};int main(){    A a;    A b;    a.x = 4;    if( a.x == a.get().x )    {        cout << "asasas   ";        cout << a.x << endl;    }    else    {        cout << "no " << a.get().x << endl;    }    b = a.get();    cout << &b << "   "<< &a << endl;    cout << "b == " << b.x << endl;    return 0;}

输出结果为

asasas   40x7ffdcfbb6650   0x7ffdcfbb6640b == 4

综上所述,return *this 返回的是对象的本身或克隆(具体看函数声明),return this 返回指针

这里我还犯过错误,在敲上述代码时,我试图看看返回的克隆对象的地址,即敲了&a.get(); 这样的语句,结果是错误的,因为该函数返回对象的克隆,即一个临时变量,而临时变量的内存地址是不可取得的

原创粉丝点击