首页 > 其他 > 详细

cpp中this与*this与引用传参

时间:2020-11-17 09:47:34      阅读:46      评论:0      收藏:0      [点我收藏+]

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
as address:0x63fe1c
p: 0x63fe1c
ps value: 123
ps address: 0x63fe10
*&p: 0x63fe1c
**&p: 123

技术分享图片

 

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

cpp中this与*this与引用传参

原文:https://www.cnblogs.com/BlueBlueSea/p/13992037.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!