[Js-C++]C++中*&(指针引用)和*(指针)的区别

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

#include <iostream>

using namespace std;
struct point {
    int x;
    int y;
};

void changenum1(point *&pnum) {
    pnum = new point;
    pnum->x = 4;
}

void changenum2(point *pnum) {
    pnum = new point;
    pnum->x = 4;
}


void test1() {
    point *num = new point;
    num->x = 10;
    changenum1(num);
    std::cout << "指针引用" << num->x << endl;
}

void test2() {
    point *num = new point;
    num->x = 10;
    changenum2(num);
    std::cout << "指针" << num->x << endl;
}

int main() {
    cout << "开始执行程序" << endl;
    test1();
    test2();
    cout << "执行程序完毕" << endl;
    return 0;
}

输出结果:

D:\Workspace\clion-workspace\star-referenceVSstar\cmake-build-debug\star_referenceVSstar.exe
开始执行程序
指针引用4
指针10
执行程序完毕

Process finished with exit code 0

 

posted @ 2018-03-24 11:10  Js_zero  阅读(17265)  评论(1编辑  收藏  举报