隨記——C++傳參、取址運算子
阿新 • • 發佈:2021-01-13
一直對C++中“ * ”、“ & ”這兩個運算子感覺很懵,心血來潮做個程式試驗試驗,加深一下對其的理解,順便做個筆記。
一、取址符“&”與引用“&”
int x = 12; int* p = &x; //定義int*型別變數並初始化,指標變數*p指向x的地址,p的值為x的地址值 cout << "p: " << p << endl; cout << "*p: " << *p << endl;
顯然,上面這段程式碼中p的值為x的地址值,即&x的值;而*p的值為x的值:12
//function1-a void function1(int* p) { int x = 12; p = &x; cout << "p: " << p << endl; cout << "*p: " << *p << endl; } int main() { int* a = new int; int b = 1; *a = b; cout << "a:" << a << endl; cout << "*a:" << *a << endl; function1(a); cout << "a:" << a << endl; cout << "*a:" << *a << endl; delete a; system("pause"); }
執行結果如下:
//function1-b void function1(int* p) { int x = 12; p = &x; cout << "p: " << p << endl; cout << "*p: " << *p << endl; } int main() { int b = 1; cout << "&b:" << &b << endl; cout << "b:" << b << endl; function1(&b); cout << "&b:" << &b << endl; cout << "b:" << b << endl; system("pause"); }
執行結果如下:
//function2
void function2(int* &p) {
int x = 12;
p = &x;
cout << "p: " << p << endl;
cout << "*p: " << *p << endl;
}int main() {
int* a = new int;
int b = 1;
*a = b;
cout << "a:" << a << endl;
cout << "*a:" << *a << endl;
function2(a);
cout << "a:" << a << endl;
cout << "*a:" << *a << endl;
delete a;
system("pause");
}
執行結果如下:
可以看出,當引數是“ *& ”型別時,這是C++中的一種型別,其引數本質上還是引用型別,是(type)*型別的引用。以function2中int* &p為例,p是int*型別的引用引數,因此在呼叫函式時引數型別必須為int*型,按程式中的定義,似function2(b)這樣書寫是錯誤的。
二、傳參,繼續理解“*&”
//function3
void swap1(int* &p, int* &q) {
int* temp;
temp = p;
p = q;
q = temp;
cout << "p and q: " << p << " " << q << endl;
cout << "*p and *q: " << *p << " " << *q << endl;
cout << "*&p and *&q: " << *&p << " " << *&q << endl;
}
void swap2(int* &p, int* &q) {
int* temp = new int;
*temp = *p;
*p = *q;
*q = *temp;
cout << "p and q: " << p << " " << q << endl;
cout << "*p and *q: " << *p << " " << *q << endl;
cout << "*&p and *&q: " << *&p << " " << *&q << endl;
delete temp;
}
int main() {
int* a, * b ;
a = new int; b = new int;
*a = 1; *b = 2;
cout << "a and b: " << a << " " << b << endl;
cout << "*a and *b: " << *a << " " << *b << endl;
swap1(a, b);
//swap2(a, b);
cout << "a and b: " << a << " " << b << endl;
cout << "*a and *b: " << *a << " " << *b << endl;
delete a, b;
system("pause");
}
swap1執行結果如下:
swap2執行結果如下:
可以看出,在swap1(a,b)中,其引數p、q直接引用a、b本身,最終結果是*a與*b二者互換指向,即地址與值都互換。而swap2(a,b)中,由於在swap2函式中只進行了值的互換,對地址並無影響,所以結果中最終*a、*b的值被互換,但所指地址並未改變。