一听就懂:C++引用的具体应用

普通引用
1.做函数参数,替代指针
2.做函数的返回值
引用指针

 

 1 #include <iostream>
 2 using namespace std;
 3 void mswap(int a, int b)
 4 {
 5     int temp;
 6     temp = a;
 7     a = b;
 8     b = temp;
 9 }
10 void mschange(int* pa, int* pb)
11 {
12     int temp;
13     temp = *pa;
14     *pa = *pb;
15     *pb = temp;
16 }
17 void msexchange(int& ma, int& mb)
18 {
19     int temp;
20     temp = ma;
21     ma = mb;
22     mb = temp;
23 }
24 /*
25     引用的用途:
26     普通引用
27     1.做函数参数,替代指针
28     2.做函数的返回值
29     引用指针
30 */
31 int getAge()
32 {
33     int age = 18;
34     return age;
35 }
36 int& getAge01()
37 {
38     static int age = 18;//局部变量,函数调用结束内存会被释放
39     return age;
40 }
41 void del(int* p)
42 {
43     p = nullptr;
44 }
45 void del01(int*& p)
46 {
47     p = nullptr;
48 }
49 int main()
50 {
51     //1.普通引用
52     //值传递不能交换两个变量的值
53     int a = 2, b = 5;
54     mswap(a, b);
55     cout << a << " " << b << endl;;
56     //地址传递可以交换两个变量的值
57     mschange(&a, &b);
58     cout << a << " " << b << endl;
59     //引用也可以交换两个变量的值
60     msexchange(a, b);
61     cout << a << " " << b << endl;
62     //引用做函数的返回值
63     //getAge() = 20;//18=20 error
64     cout << getAge() << endl;
65     getAge01() = 22;
66     cout << getAge01() << endl;
67     //2.引用指针
68     int* pNew = new int;
69     del(pNew);
70     cout << pNew << endl;
71     del01(pNew);
72     cout << pNew << endl;
73     return 0;
74 }

 

posted @ 2025-02-12 23:29  java帝国  阅读(4)  评论(0)    收藏  举报