• cpp中this与*this与引用传参


    https://blog.csdn.net/stpeace/article/details/22220777#

    1.this与*this例子

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

    return this返回当前对象的地址(指向当前对象的指针),

    如果返回*this:

    #include <iostream>
    using namespace std;
     
    class A
    {
    public:
        int x;
        A& get()
    //如果返回A会报错:error: taking address of temporary [-fpermissive]
    //不能获取临时变量的地址,因为会产生拷贝
        {
            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
    yes

    如果返回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

    2.*与&的区别

    https://www.cnblogs.com/mr-stn/p/9037773.html,举的例子非常好。

    #include<iostream>
    using namespace std;
    int main(){
        int a=123;
        //&a表示a在内存中的地址,也就是123在内存中的地址
        cout<<"a: "<<a<<endl<<"a's address:"<<&a<<endl;
        //此时p是一个指针,指向a所在的位置
        int *p=&a;
        cout<<"p: "<<p<<endl;
        //声明p之后,在p之前添加*表示p指向内存的值
        cout<<"p's value: "<<*p<<endl;
        //同时p也是 一个变量,在内存中也有一个地址储存它,但其地址不是a的地址
        cout<<"p's address: "<<&p<<endl;
        //试试*&组合使用是什么效果
        cout<<"*&p: "<<*&p<<endl;
        //&p是一个内存地址,*&p表示&p指向地址内存空间的值,在这里表示a的地址
        cout<<"**&p: "<<**&p<<endl;
        //刚才我们已经知道*&p是a的地址,那么**&p就表示a的值
    return 0;}

    输出:

    a: 123
    a's address:0x63fe1c
    p: 0x63fe1c
    p's value: 123
    p's address: 0x63fe10
    *&p: 0x63fe1c
    **&p: 123

     p本身就是一个变量,一个指针变量,它也需要占据存储空间,而引用只是别名,不占用存储空间。

  • 相关阅读:
    python imageai 对象检测、对象识别
    flask跨域请求三行代码搞定
    图片压缩-KMeans
    电影天堂
    python 时间操作
    时间HTML
    3D滚动效果
    tensorflow基础
    studio显示Surface: getSlotFromBufferLocked: unknown buffer: 0xa2a58be0
    解决github访问慢和clone慢解决方案
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/13992037.html
Copyright © 2020-2023  润新知