C++中*&和*的区别

在C语音中*代表指针,&代表地址

在C++中*代表指针,而&代表引用,而*&代表指针引用

复习一下,指针是一个变量(它的值是一个地址),而指针引用指的是这个变量的引用;在C++中如果参数不是引用的话会调用参数对象的拷贝构造函数,所以如果有需求想改变指针所指的对象(换句话说,就是要改变指针里面存的地址),就要使用指针引用,在网上看到大佬的代码,简单明了,如下

#include <iostream>

using namespace std;

struct Point {
    int x;
    int y;
};

/*指针*/
void test1(Point *p)
{
    p = new Point();
    p->x = 100;
}

/*指针引用*/
void test2(Point *&p)
{
    p = new Point();
    p->x = 100;
}

int main(int argc, char const *argv[])
{
    Point *p1 = new Point();
    Point *p2 = new Point();
    p1->x = 1;
    p2->x = 1;

    cout << "p1->x = " << p1->x << "; p2->x = " << p2->x << endl;

    test1(p1);
    test2(p2);

    cout << "p1->x = " << p1->x << "; p2->x = " << p2->x << endl;

    return 0;
}

执行结果

yishurufa@ubuntu:~/works/program$ vim test.cpp 
yishurufa@ubuntu:~/works/program$ g++ test.cpp 
yishurufa@ubuntu:~/works/program$ ./a.out 
p1->x = 1; p2->x = 1
p1->x = 1; p2->x = 100

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值