1.引用做函数参数(1.值传递,2.地址传递,3.引用传递)
#include <iostream>
using namespace std;
//1.值传递
void swap01(int a, int b)//a,b形参
{
int temp = a;
a = b;
b = temp;
cout << "swap01 a=" << a << endl;
cout << "swap01 b=" << b << endl;
}
//2.地址传递
void swap02(int* p, int* p2)
{
int temp = *p;
*p = *p2;
*p2 = temp;
cout << "swap02 *p=" << *p << endl;
cout << "swap02 *p2=" << *p2 << endl;
}
//3.引用传递
void swap03(int& a2, int& b2) {
int temp = a2;
a2 = b2;
b2 = temp;
cout << "swap03 a2=" << a2 << endl;
cout << "swap03 b2=" << b2 << endl;
}
int main()
{
//指针和函数
//1.值传递
int a = 10;
int b = 20;
swap01(a, b);//实参a,b的值传到形参a,b
cout << "a=" << a << endl;//a=10
cout << "b=" << b << endl;//b=20
//值传递形参改变不会影响实参,想结果改变得返回值出来
//2.地址传递
swap02(&a, &b);
cout << "a=" << a << endl;//a=20
cout << "b=" << b << endl;//b=10
//地址传递可以修饰实参(改变实参)
//3.引用传递
int a2 = 10;
int b2 = 20;
swap03(a2, b2);
cout << "a=" << a2 << endl;//a=20
cout << "b=" << b2 << endl;//b=10
//地址传递也可以修饰实参(改变实参)
system("pause");
return 0;
}
结果
swap01 a=20
swap01 b=10
a=10
b=20
swap02 *p=20
swap02 *p2=10
a=20
b=10
swap03 a2=20
swap03 b2=10
a=20
b=10
2.引用做函数返回值
#include <iostream>
using namespace std;
//引用做函数的返回值
//1.不要返回局部变量的引用
int& test01()
{
int a = 10;//局部变量存放在栈区
return a;
}
//2.函数的调用可以作为左值
int& test02()
{
static int b = 10;//静态变量,存放在全局区,全局区上的数据在程序结束后系统释放
return b;
}
int main()
{
int& ref = test01();
cout << ref << endl;//第一次可以打印正确,是因为编译器做了保留
cout << ref << endl;//第二次就不在保留
cout << ref << endl;
int& ref2 = test02();
cout << ref2 << endl;
cout << ref2 << endl;//不会自动释放
cout << ref2 << endl;
test02() = 1000;//改变原名的值
//如果函数的返回值是引用,这个函数调用可以作为左值
cout << ref2 << endl;//改变原名的值,引用后的别名也会改变
cout << ref2 << endl;//不会自动释放
cout << ref2 << endl;
system("pause");
return 0;
}
结果
10
2047187336
2047187336
10
10
10
1000
1000
1000
3.引用的本质在C++内部中是一个指针常量