黑马程序员C++核心编程笔记--2 引用
2.1引用的基本语法
2.2 引用传参
2.3 引用的注意事项
前三节知识点新版课程已有记录, 详见16.引用的基本概念、17.引用传参、16.引用的基本概念
2.4 引用做函数返回值
#include <iostream>
using namespace std;// 1.不要返回局部变量的引用int& test0() {int a = 10; // 局部变量存放在四区中的栈区return a;
}// 2.函数的调用可以作为左值
int& test1() {static int a = 10; // 静态变量存放在四区中的全局区,静态变量在函数调用结束后,不会被释放return a;
}
int main() {// int &ref = test0();// cout << ref << endl; // c++20无法输出,c++11可以输出一次,因为编译器做了保留,输出第二次结果错误,因为内存已经释放int& ref = test1(); // ref用别名的方式访问a的内存cout << ref << endl;cout << ref << endl; //无论输出几次,结果都是10// 函数的调用可以作为左值test1() = 1000; // 给a的引用赋值1000cout << test1() << endl;cout << test1() << endl;return 0;}
2.5 引用的本质
引用的本质在c++内部实现是一个指针常量
讲解示例:
#include <iostream>
using namespace std;// 发现是引用,转换为int * const ref = &a
void func(int &ref) {ref = 100; //ref是引用,转换为 *ref = 100
}int main() {int a = 10;// 自动转换为 int* const ref = &a;指针常量是指针指向不可更改,也说明引用为什么不可更改int& ref = a;ref = 20;cout << "a:" << a << endl;cout << "ref:" << ref << endl;return 0;
}
2.6 常量引用
作用:常量引用主要用来修饰形参,防止误操作
在函数形参列表中,可以加const修饰形参,防止形参改变实参
示例:
#include <iostream>
using namespace std;// 打印数据函数
void showValue(int& a) {a = 1000; // 误操作在函数内修改了参数值会导致函数外的变量值也改变cout << "val = " << a << endl;
}// 为了防止误操作,将参数改为常量引用
void showValue(const int& a) {// a = 1; // 错误❌,常量引用只读,不能被修改cout << "val = " << a << endl;
}int main() {// 常量引用int a = 10;// int& ref = 10; // 报错❌,原因是引用必须引一块合法的内存空间const int& ref = 10; // 正确。加上const后编译器将代码修改为 int temp = 10; int& ref = temp;// ref = 20; // 错误❌,常量引用只读,不能被修改cout << a << endl;cout << ref << endl;int b = 100;showValue(b);cout << "b = " << b << endl;// 使用场景修饰形参,防止误触操作int c = 10;showValue(c);cout << "c = " << c << endl;}