代码1:
#include<iostream>
using namespace std;
//引用就是给变量起别名
//语法:数据类型 &别名=原名
/*注:
* 1.引用必须初始化 int &b; 错误代码
* 2.引用初始化后,不可以改变
*/
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");
}
结果:
a=10
b=10
a=100
b=100
代码2:
#include<iostream>
using namespace std;
//引用做函数参数
//交换函数
//1.值传递
void swap1(int a, int b)
{
int c;
c = a;
a = b;
b = c;
}
//2.地址传递
void swap2(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
//3.引用传递
void swap3(int& a, int& b)
{
int c;
c = a;
a = b;
b = c;
}
int main()
{
int a = 10;
int b = 20;
swap1(a, b); //值传递 形参不会修饰实参
cout << "swap1 a=" << a << endl;
cout << "swap1 b=" << b << endl;
swap2(&a, &b); //地址传递 形参会修饰实参
cout << "swap2 a=" << a << endl;
cout << "swap2 b=" << b << endl;
swap3(a, b); //引用传递 形参会修饰实参
cout << "swap3 a=" << a << endl;
cout << "swap3 b=" << b << endl;
system("pause");
}
结果:
swap1 a=10
swap1 b=20
swap2 a=20
swap2 b=10
swap3 a=10
swap3 b=20
代码3:
#include<iostream>
using namespace std;
//引用做函数返回值
//1.不要返回局部变量的引用
int& test01()
{
int a = 10;
return a;
}
//2.函数的调用可以作为左值
int& test02()
{
static int a = 10;//静态变量 存放在全局区 全局区上的数据在程序结束后系统释放
return a;
}
int main()
{
//int& b = test01();
//cout << "b=" << b <<endl; //第一次结果正确 是因为编译做了保留
//cout << "b=" << b << endl; //第二次出错 是因为a的内存已经释放
int& ref2 = test02();
cout << "ref2=" << ref2 << endl;
cout << "ref2=" << ref2 << endl;
test02() = 1000; //如果函数的返回值是引用 这个函数调用可以作为左值
cout << "ref2=" << ref2 << endl;
cout << "ref2=" << ref2 << endl;
system("pause");
}
结果:
ref2=10
ref2=10
ref2=1000
ref2=1000
代码4:
#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; //内部发现ref是引用 自动帮我们转换为 *ref=20
cout << "a=" << a << endl;
cout << "ref=" << ref << endl;
func(a);
system("pause");
}
结果:
a=20
ref=20
代码5:
#include<iostream>
using namespace std;
void showValue(const int &a)
{
//a = 1000;
cout << "a=" << a << endl;
}
int main()
{
//常量引用
//使用场景:用来修饰形参,防止误操作
//加上const后,编译器将代码修改 int temp=10;const int &ref=temp;
const int& ref = 10;//引用必须引一块合法的内存空间
//ref = 20; //加入const后变成只读,不可以修改
int a = 100;
showValue(a);
system("pause");
}
结果:
a=100