1 引用的基本使用
作用: 给变量起别名。
语法: 数据类型 &别名 = 原名
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <iostream> using 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;
system("pause"); return 0; }
|
输出:
1 2 3 4
| a = 10 b = 10 a = 100 b = 100
|
2 引用注意事项
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream> using namespace std;
int main() {
int a = 10; int b = 20; int &c = a; c = b;
cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl;
system("pause"); return 0; }
|
输出:
3 引用做函数参数
作用:函数传参时,可以利用引用的技术让形参修饰实参。
优点:可以简化指针修改实参。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| #include <iostream> using namespace std;
void mySwap01(int a, int b) { int temp = a; a = b; b = temp; }
void mySwap02(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }
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 << "a:" << a << " b:" << b << endl;
mySwap02(&a, &b); cout << "a:" << a << " b:" << b << endl;
mySwap03(a, b); cout << "a:" << a << " b:" << b << endl;
system("pause"); return 0; }
|
输出:
1 2 3
| a:10 b:20 a:20 b:10 a:10 b:20
|
总结:通过引用参数产生的效果同按地址传递是一样的。引用的语法更清楚简单
4 引用做函数返回值
作用:引用是可以作为函数的返回值存在的。
注意:不要返回局部变量引用。
用法:函数调用作为左值。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <iostream> using namespace std;
int& test01() { int a = 10; return a; }
int& test02() { static int a = 20; return a; }
int main() {
int& ref = test01(); cout << "ref = " << ref << endl; cout << "ref = " << ref << endl;
int& ref2 = test02(); cout << "ref2 = " << ref2 << endl; cout << "ref2 = " << ref2 << endl;
test02() = 1000;
cout << "ref2 = " << ref2 << endl; cout << "ref2 = " << ref2 << endl;
system("pause"); return 0; }
|
输出:
1 2 3 4 5 6
| test01()函数报错:error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
ref2 = 20 ref2 = 20 ref2 = 1000 ref2 = 1000
|
5 引用的本质
本质:引用的本质在c++内部实现是一个指针常量。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <iostream> using namespace std;
void func(int& ref){ ref = 100; } int main(){ int a = 10; int& ref = a; ref = 20; cout << "a:" << a << endl; cout << "ref:" << ref << endl; func(a); return 0; }
|
结论:C++推荐用引用技术,因为语法方便,引用本质是指针常量,但是所有的指针操作编译器都帮我们做了。
6 常量引用
作用:常量引用主要用来修饰形参,防止误操作。
在函数形参列表中,可以加const修饰形参,防止形参改变实参。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #include <iostream> using namespace std;
void showValue(const int& v) { cout << v << endl; }
int main() {
const int& ref = 10;
cout << ref << endl;
int a = 10; showValue(a);
system("pause"); return 0; }
|