return *this和return this的区别

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

      正确答案为:return *this返回的是当前对象的克隆(固然, 这里仅考虑返回类型为A 没有考虑返回类型为A& )。return this返回当前对象的地址(指向当前对象的指针), 下面咱们来看看程序吧: ios

#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 this

 

      再看: spa

#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 htm

no 对象

相关文章
相关标签/搜索