C++ Reference Variable 參考
概念
參考是變數別名,當參考被改變變數的值也會改變。
常常用在傳入函式的參數,因為一般的變數傳入函式中是複製一份去做計算,
但是參考的話是複製位址,因此更改後不會因為離開函式而變回原本的值。
另外,以參考為參數傳入函式,可以避免stack overflow的問題,
因為參考是複製位址,並非複製整個變數。
語法示範
- 以&為開頭表示使用參考,與取址一樣的符號,但在宣告時使用即是代表要做參考
ex:
string name = "Tony";
// 使用參考
string &nickName = name;
// 取地址
cout << &name << endl;
- 使用參考時必須一開始就初始化
- 參考一旦決定了為那個變數的參考後便不能再更改
ex:
string name = "Tony";
string &nickname = name;
string otherName = "Annie";
&nickname = otherName; // 錯誤
- const參考與其他變數使用const相同,不能更改
ex:
string testName = "test";
const string &ref = testName;
testName = "pass";
cout << testName << endl; // output: pass
cout << ref << endl; // output: pass
// const can't be changed
ref = "impossible"; // error
- 範例
#include <iostream>
using namespace std;
int main() {
string name = "Tony";
string others = "Annie";
string &nickname = name;
// reference need to be initialized at beginning
// error : string &wrong;
// reference can not change the connection
// error : &nickname = others; // because nickname is the reference of name
// const can not be changed
string testName = "test";
const string &ref = testName;
testName = "pass";
cout << testName << endl; // output: pass
cout << ref << endl; // output: pass
// const can't be changed
// error : ref = "impossible";
cout << "name: " << name << ", address: " << &name <<endl; // name: Tony, address: 0x7fff59f9e918
cout << "nickname: " << nickname << ", address: " << &nickname <<endl; // name: Tony, address: 0x7fff59f9e918
nickname = "Tom";
cout << "name: " << name << ", address: " << &name <<endl; // name: Tom, address: 0x7fff59f9e918
cout << "nickname: " << nickname << ", address: " << &nickname <<endl; // name: Tom, address: 0x7fff59f9e918
name = "James";
cout << "name: " << name << ", address: " << &name <<endl; // name: James, address: 0x7fff59f9e918
cout << "nickname: " << nickname << ", address: " << &nickname <<endl; // name: James, address: 0x7fff59f9e918
}
應用
#include <iostream>
using namespace std;
void swapNormal(int, int);
void swapRef(int &, int &);
int main() {
int a = 1000;
int b = 10;
cout << "Without any manipulation..." << endl;
cout << "a: " << a << endl;
cout << "b: " << b << endl;
swapNormal(a, b);
cout << "After swapNormal:" << endl;
cout << "a : " << a << endl;
cout << "b : " << b << endl;
swapRef(a, b);
cout << "After swapRef:" << endl;
cout << "a : " << a << endl;
cout << "b : " << b << endl;
}
void swapNormal(int x, int y) {
cout << "In swapNormal..." << endl;
/*
複製一份
x = a;
y = b;
*/
int tmp;
tmp = x;
x = y;
y = tmp;
cout << "a: " << x << endl;
cout << "b: " << y << endl;
}
void swapRef(int &x, int &y) {
cout << "In swapRef..." << endl;
/*
複製一份
&x = a;
&y = b;
*/
int tmp;
tmp = x;
x = y;
y = tmp;
cout << "a: " << x << endl;
cout << "b: " << y << endl;
}
output:
Without any manipulation...
a: 1000
b: 10
In swapNormal...
a: 10
b: 1000
After swapNormal:
a : 1000
b : 10
In swapRef...
a: 10
b: 1000
After swapRef:
a : 10
b : 1000
沒有留言:
張貼留言