本文共 3038 字,大约阅读时间需要 10 分钟。
引用:
作用:给变量起别名 语法:数据类型 &别名=原名
#includeusing namespace std;int main(){ // 引用基本语法 // 数据类型 &别名 = 原名 int a = 10; int& b = a; cout << "a = " << a << endl; cout << "b = " << b << endl; b = 100; cout << "a = " << a << endl; cout << "b = " << b << endl;}
#includeusing namespace std;int main(){ // 1.引用必需初始化 // int &b; 错误 // 2.引用一旦初始化后,就不可以更改 int a = 10; int& b = a; int c = 100; b = c; // 这是赋值操作,而不是更改引用 cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl;}
引用做函数参数
作用:函数传参时,可以利用引用的技术让形参修饰实参 优点:可以简化指针修改实参
#includeusing namespace std;// 交换函数//1. 值传递void mySwap01(int a,int b) { int temp = a; a = b; b = temp; cout << "mySwap01 a = " << a << endl; cout << "mySwap01 b = " << b << endl;}//2. 地址传递void mySwap02(int *a,int *b) { int temp = *a; *a = *b; *b = temp;}//3.引用传递void mySwap03(int &a,int &b) { int temp = a; a = b; b = temp;}int main(){ int a = 10; int b = 20; mySwap01(a, b); // 值传递,形参不会修饰实参 cout << "a1 = " << a << endl; cout << "b1 = " << b << endl; mySwap02(&a, &b); // 地址传递,形参会修饰实参 cout << "a2 = " << a << endl; cout << "b2 = " << b << endl; int c = 30; int d = 40; mySwap03(c, d); //引用传递,形参会修饰实参 cout << "c = " << c << endl; cout << "d = " << d << endl;}
总结:通过引用参数产生的效果同按地址传递是—样的。引用的语法更清楚简单
引用做函数返回值:
作用:引用是可以作为函数的返回值存在的 用法:函数调用作为左值 注意:不要返回局部变量引用
#includeusing namespace std;// 引用做函数的返回值// 1.不要返回局部变量的引用int& test01() { int a = 10; return a;}// 2.函数的调用可以作为左值int main(){ int& ref = test01(); cout << "ref = " << ref << endl; // 第一次正确,因为编译器做了保留 cout << "ref = " << ref << endl; // 第二次,就不保留了}
#includeusing namespace std;// 引用做函数的返回值// 1.不要返回局部变量的引用int& test01() { int a = 10; return a;}// 2.函数的调用可以作为左值int& test02() { static int a = 10; return a;}int main(){ int& ref = test02(); cout << "ref = " << ref << endl; cout << "ref = " << ref << endl; // 作为左值 test02() = 1000; cout << "ref = " << ref << endl; cout << "ref = " << ref << endl;}
引用的本质
本质:引用的本质在c++内部实现是一个指针常量
#includeusing namespace std;// 发现是引用,转化为 int * const ref = &a;void func(int& ref) { ref = 100; //ref 是引用,转换为 * ref = 100}int main(){ int a = 100; // 自动转化为 int * const ref = &a;指针常量是指针指向不可改,也说明为什么引用不可更改 int& ref = a; ref = 20; // 内部发现ref是引用,自动帮我们转化为:*ref = 20; cout << "a :" << a << endl; cout << "ref :" << ref << endl; func(a); return 0;}
结论:C++推荐用引用技术,因为语法方便,引用本质是指针常量,但是所有的指针操作编译器都帮我们做了
常量引用
作用:常量引用主要用来修饰形参,防止误操作 在函数形参列表中,可以加const修饰形参,防止形参改变实参
#includeusing namespace std;// 打印数据函数void showValue(const int& val) { // val = 1000; 不可修改 cout << "val =" << val << endl;}int main(){ // 常量引用 // 使用场景:用来修饰形参,防止误操作 // int &ref = 10; 错误 // 加上 const 之后,编译器将代码修改 int temp = 10; const int & ref = temp; // const int& ref = 10;//引用必需引一块合法的内存空间 // ref = 20; // 错误,加入const 之后变为只读,不可以修改 int a = 200; showValue(a); cout << "a =" << a << endl; return 0;}
转载地址:http://xfctz.baihongyu.com/