1. 程式人生 > >指針與引用

指針與引用

name code -s strong ron 改變 變量 pan coo

引用類型:

引用指變量的別名

基本的引用:

 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     int a = 3;
 5     int &b = a;
 6 
 7     b = 10;
 8     cout << a << endl;
 9     return 0;
10 }

b作為a的引用,當對b進行賦值時a的值也隨之改變。

結構體的引用:

 1 #include <iostream>
 2 using namespace
std; 3 typedef struct { 4 int x; 5 int y; 6 }Coor; 7 int main() { 8 Coor c1; 9 Coor &c = c1; 10 c.x = 10; 11 c.y = 20; 12 cout << c1.x << c1.y << endl; 13 return 0; 14 }

對c1的引用c的結構成員賦值,即使對c1賦值

指針類型的引用:

類型*&引用指針別名 = 指針;

 1 #include <iostream>
 2
using namespace std; 3 int main() { 4 int a = 10; 5 int *p = &a; 6 int *&q = p; 7 *q = 20; 8 cout << a << endl; 9 return 0; 10 }

引用做函數參數:

使用指針對主函數的變量賦值的函數

 1 #include <iostream>
 2 using namespace std;
 3 void fun(int *a, int *b) {
 4     int
c = 0; 5 c = *a; 6 *a = *b; 7 *b = c; 8 } 9 int main() { 10 int x = 10, y = 20; 11 fun(&x, &y); 12 return 0; 13 }

使用引用對主函數的變量賦值的函數

 1 #include <iostream>
 2 using namespace std;
 3 void fun(int &a, int &b) {
 4     int c = 0;
 5     c = a;
 6     a = b;
 7     b = c;
 8 }
 9 int main() {
10     int x = 10, y = 20;
11     fun(x, y);
12     return 0;
13 }

指針與引用