引言

C++包含了C语言的全部语法,任何合法的C语言程序,都是合法的C++程序
C++还在C的基础上做了很多扩展,主要是为了实现面向对象编程和泛型编程
不过既然是第一章,先讲些和面向对象以及泛型关系不太大的扩展

引用的概念

3.PNG

  1. #include<iostream>
  2. using namespace std;
  3. int main(void)
  4. {
  5. int n=4;
  6. int &r=n;
  7. r=4;
  8. cout<<n<<endl;//4
  9. n=5;
  10. cout<<r<<endl;//5
  11. return 0;
  12. }

引用的性质

4.PNG

  1. #include<bits/stdc++.h>
  2. //这是C++万能头文件,包含了目前C++所有核心头文件,包括
  3. /*#include <iostream>
  4. #include <cstdio>
  5. #include <fstream>
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <deque>
  9. #include <vector>
  10. #include <queue>
  11. #include <string>
  12. #include <cstring>
  13. #include <map>
  14. #include <stack>
  15. #include <set>*/
  16. using namespace std;
  17. int main(void)
  18. {
  19. double a=4,b=5;
  20. double &r1=a;
  21. double &r2=r1;//r2也引用a
  22. r2=10;
  23. cout<<a<<endl;//10
  24. r1=b;//r1没有引用b,这里仅仅进行赋值操作
  25. cout<<a<<endl;//5
  26. return 0;
  27. }

引用的应用

1.作为函数形参,在函数中修改外部变量的值(类似于指针)

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. void valueExchange(int&,int&);
  4. int main(void)
  5. {
  6. int a=4,b=5;
  7. valueExchange(a,b);
  8. cout<<a<<endl;//5
  9. cout<<b<<endl;//4
  10. return 0;
  11. }
  12. void valueExchange(int &x,int &y)
  13. {
  14. int temp;
  15. temp=x;
  16. x=y;
  17. y=temp;
  18. return;
  19. }

2.作为函数返回值

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n=5;
  4. int &setValue()
  5. {
  6. return n;
  7. }
  8. int main(void)
  9. {
  10. setValue()=40;
  11. cout<<n;//40
  12. return 0;
  13. }

常引用

5.PNG
6.PNG

常引用和非常引用的转换

7.PNG

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(void)
  4. {
  5. int n=5;
  6. int &r1=n;
  7. const int &r=r1;
  8. cout<<r;//编译通过,输出5
  9. return 0;
  10. }
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(void)
  4. {
  5. int n=5;
  6. const int &r1=n;
  7. int &r=r1;//编译错误
  8. cout<<r;
  9. return 0;
  10. }