版权声明:本博客主要记录学习笔记和遇到的一些问题解决方案,转载请注明出处! https://blog.csdn.net/u010982507/article/details/81140662
使用
1、引用就是变量的别名,通常用在函数的形参列表中。
2、定义引用的语法格式是在变量前面加’&’符号,指向的是变量地址。
3、引用声明的时候必须赋值。
实例
#include <iostream>
#include <string>
using namespace std;
// 使用值交换
void swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
cout << a << "," << b << endl;
}
// 使用引用交换
void swaps(int &a,int &b) {
int temp;
temp = a;
a = b;
b = temp;
cout << a << "," << b << endl;
}
int main() {
int a = 2;
int b = 3;
//swap(a,b); // 输出结果是2,3
swaps(a,b); // 输出结果是3,2
cout << a << "," << b << endl;
system("pause");
return 0;
}