跳到主要内容

10,引用

2.1作用:给变量起别名

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;
}

2.2引用的注意事项

引用必须要初始化 (int &b;是错误的)

引用一旦初始化后,就不可以更改了

int main()
{
int a = 10;
int &b = a;

int c = 20;
b = c;//赋值操作

cout<<"a = "<< a <<endl;
cout<<"b = "<< b <<endl;
cout<<"c = "<< c <<endl;

system("pause");
return 0;
}

2.3引用做函数参数

作用:函数传参时,可以利用引用的技术让形参修饰实参

优点:可以简化指针修改实参

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);
//myswap02(&a, &b);
myswap03(a, b);

cout<<"a = "<< a <<endl;
cout<<"b = "<< b <<endl;

system("pause");
return 0;
}

2.4引用做函数返回值

作用:引用是可以作为函数的返回值存在的

注意:不要返回局部变量引用

用法:函数调用作为左值

int &test01()
{
int a = 10;//栈区
return a;
}

int& test()
{
static int a = 10;//全局区
return a;
}

int main()
{
int &ref1 = test01();
cout<<"ref1 = "<< ref << endl;//第一次正确,编译器做了保留
cout<<"ref1 = "<< 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;
}

2.5引用的本质

本质:引用的本质在C++内部实现是一个指针常量

void func(int& ref)
{
ref = 100;
}

int main()
{
int a = 10;
//自动转换为int *const ref = &a;指针常量是指针指向不可改,也说明为什么引用不可更改
int &ref = a;
ref = 20;//*ref = 20;
cout<<"a: "<< a <<endl;
cout<<"ref: "<< ref <<endl;
func(a);
return 0;
}

2.6常量引用

作用:常量引用主要修饰形参,防止误操作,防止形参改变为实参

void showValue(const int& v)
{
//v = 100;//是错误的
cout << "v = "<< v <<endl;
}

int main()
{
//int a = 10;
//int & ref = 10;//是错误的
//const int & ref = 10;//必须引用一块合法的内存空间
//ref = 20;不可以修改

int a = 100;
showValue(a);
cout<<"a = "<< a <<endl;

system("pause");
return 0;
}

参考与致谢