[Js-C++]C++中*&(指針引用)和*(指針)的區別

好久以前學的C++了,複習一下,指針是一個存放地址的變量,而指針引用指的是這個變量的引用,衆所周知C++中若是參數不是引用的話會調用參數對象的拷貝構造函數,因此若是有需求想改變指針所指的對象(換句話說,就是要改變指針裏面存的地址),就要使用指針引用,在網上看到大佬的代碼,簡單明瞭,以下ios

#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
相關文章
相關標籤/搜索