引用即别名。引用不是对象,只是为已经存在的对象所起的另一个名字。
格式:数据类型 &别名 = 原名
注意点:
1)引用必须初始化,初始化后不可改变。
2)不能定义引用的引用(因为引用不是对象)。
3)引用可作为函数参数(值传递,地址传递,引用传递)
4)引用作为函数返回值,不可以返回局部变量的引用。
例子:
int& func()
{
int num = 10; //局部变量在栈区
return num;
}
int main()
{
int& ref = func();
cout << "ref = " << ref << endl;
//cout << "ref = " << ref << endl;
return 0;
}
codeblocks无返回结果,会出现错误信息。
5)引用是函数返回值,函数调用可作为左值
例子:
int& func()
{
static int num = 10; //静态变量在全局区
return num;
}
int main()
{
int& ref = func();
cout << "ref = " << ref << endl;
func() = 20; //相当于做了num=20的操作
cout << "ref = " << ref << endl; //ref又是num的别名,所以也是20
return 0;
}
输出结果:
ref = 10
ref = 20
6)引用本质:引用在C++内部实现是一个指针常量
例子:
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);
return 0;
}
原文:https://www.cnblogs.com/echobiscuit/p/12912255.html