zoukankan      html  css  js  c++  java
  • return *this和return this的区别

     别跟我说, 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

  • 相关阅读:
    vue移动端滚动插件BetterScroll
    vue商品推荐信息展示 案例
    css吸顶效果
    vue TabControl案例
    首页导航栏样式 案例
    HO引擎近况20210713
    go定时器--timer
    go定时器--Ticker
    Go测试--main测试
    Spring 核心技术 AOP 实例
  • 原文地址:https://www.cnblogs.com/hdk1993/p/4355472.html
Copyright © 2011-2022 走看看