2.引用
2.1引用的基本使用
2.2引用注意事项
- 引用必须初始化
- 引用在初始化后,不可以改变
- 无论是操作别名,还是操作原名,都是操作同一块内存
#include<iostream>
using namespace std;
int main()
{
int num1 = 12;
int num2 = 25;
int &num = num1;
num = num2;
cout << num << endl;
cout << num1 << endl;
cout << num2 << endl;
system("pause");
return 0;
}
2.3引用做函数参数
- 函数传参时,可以利用引用的技术让形参修饰实参
- 可以简化指针修改实参
#include<iostream>
using namespace std;
void SwapNum(int a, int b);
void SwapAdd(int* a, int* b);
void SwapRef(int& a, int& b);
int main() {
int a = 10;
int b = 20;
SwapNum(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
SwapAdd(&a, &b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
SwapRef(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
void SwapNum(int a, int b) {
int temp = a;
a = b;
b = temp;
}
void SwapAdd(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void SwapRef(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
2.4引用做函数返回值
- 引用是可以作为函数的返回值存在的
- 不要返回局部变量引用
- 函数调用为左值
#include<iostream>
using namespace std;
int& test_1();
int& test_2();
int main() {
int& ref = test_1();
cout << "ref = " << ref << endl;
cout << "ref = " << ref << endl;
int& ref2 = test_2();
cout << "ref2 = " << ref2 << endl;
cout << "ref2 = " << ref2 << endl;
cout << "ref2 = " << ref2 << endl;
test_2() = 1000;
cout << "ref2 = " << ref2 << endl;
system("pause");
return 0;
}
int& test_1() {
int a = 10;
return a;
}
int& test_2() {
static int a = 10;
return a;
}
2.5引用的本质
#include<iostream>
using namespace std;
void func(int& ref);
int main() {
int a = 10;
int& ref = a;
ref = 20;
cout << "a = " << a << endl;
cout << "ref = " << ref << endl;
func(a);
cout << "ref = " << ref << endl;
system("pause");
return 0;
}
void func(int& ref) {
ref = 100;
}
2.6常量引用
- 作用: 常量引用主要用来修饰形参,防止误操作
- 在函数形参列表中,可以加const修饰形参,防止形参改变实参
#include<iostream>
using namespace std;
void showValue(int& value);
int main() {
int a = 10;
int& ref = a;
const int& ref2 = 10;
int num = 1000;
showValue(num);
system("pause");
return 0;
}
void showValue(int& value) {
cout << "value = " << value << endl;
}
void showValue(const int& value) {
cout << "value = " << value << endl;
}