引用的基础知识

 1 #include<iostream>
 2 using namespace std;
 3 //1 引用的概念
 4 //2 属于C++编译器对C的扩展,不能用C语言的语法去思考它
 5 void main1()
 6 {
 7     int  a = 10;
 8     //引用的语法:Type& name=var;
 9     int &b = a;//b是a的别名,可通过b操作a
10     b = 100;//相当于把a修改成了100了
11     printf("b:%d\n", b);
12     printf("a:%d\n", a);
13     a = 200;
14     printf("b:%d\n", b);
15     printf("a:%d\n", a);
16     system("pause");
17     return;
18 }
19 //3 普通引用必须要初始化
20 void main2()
21 {
22     int a = 10;
23     int &b = a;
24     //int &c; 
25     system("pause");
26 }
27 
28 //基础类型的引用
29 void myswap(int a, int b)
30 {
31     int c;
32     c = a;
33     a = b;
34     b = c;
35 }
36 
37 void myswap2(int *a, int *b)
38 {
39     int c;
40     c = *a;
41     *a = *b;
42     *b = c;
43 }
44 
45 //4 引用作为函数参数声明时不进行初始化
46 void myswap3(int &a, int &b)
47 {
48     int c;
49     c = a;
50     a = b;
51     b = c;
52 }
53 
54 void main()
55 {
56     int x, y;
57     x = 10;
58     y = 20;
59     myswap(x, y);
60     printf("x:%d,y:%d\n", x, y);
61 
62     myswap2(&x, &y);
63     printf("x:%d,y:%d\n", x, y);
64 
65     //a就是x的别名,b就是y的别名
66     myswap3(x, y);
67     printf("x:%d,y:%d\n", x, y);
68 
69     system("pause");
70 }

 

posted @ 2017-03-23 17:04  Shaine  阅读(218)  评论(0编辑  收藏  举报