指標&參考

Pointer & Reference

指標

一個變數, 存放一個記憶體位址, 指向另一個變數.

變數型態 *變數名稱 = &另一個變數;
#include <iostream>
using namespace std;
int main(){
    int a = 10;
    int *p = &a;
    cout << p;  // 0x7fff683232a4
}

取址符號 &

#include <iostream>
using namespace std;
int main(){
    int a = 10;
    cout << a; // 10
    cout << &a; // 0x7ffec663074c
}

獲取變數的記憶體位址

取值符號 *

獲取指標存的值

#include <iostream>
using namespace std;
int main(){
    int a = 10;
    int *p = &a; // 宣告指標
    cout << p; // 0x7ffec663074c
    cout << *p; // 10
}

參考 

一個變數的別名, 可以讓一個變數等同於另一個變數.

變數型態 &變數名稱 = 原變數;
#include <iostream>
using namespace std;
int main(){
    int a = 3;
    int &r = a;
    cout << r; // 3
}

參考 

#include <iostream>
using namespace std;

void add(int a) {
    a++;
}

int main(){
	int x = 5;
	add(x);
    cout << x << endl;  // 5
}
#include <iostream>
using namespace std;

void add(int &a) {
    a++;
}

int main(){
	int x = 5;
	add(x);
    cout << x << endl;  // 6
}

review

By ariel tai

review

  • 5