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本身就是一个变量,一个指针变量,它也需要占据存储空间,而引用只是别名,不占用存储空间。

posted @   lypbendlf  阅读(461)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2018-11-17 PAT 1082 Read Number in Chinese[难]
2018-11-17 PAT 1135 Is It A Red-Black Tree[难]
2018-11-17 PAT 1127 ZigZagging on a Tree[难]
点击右上角即可分享
微信分享提示