c++ 基础知识-引用
引用的本质是指针常量
1.引用基础
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a =10;
int c = 15;
int &b = a;//引用必须初始化
//int &b = c;// “b”: 重定义;多次初始化,引用只能初始化依次,不可以更改
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
return 0;
}
2.引用作为函数参数
#include <iostream>
#include <string>
using namespace std;
void swapTest(int &a,int &b)//不用指针也可以
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
swapTest(a,b);
cout<<"a : "<<a<<endl;
cout<<"b : "<<b<<endl;
return 0;
}
3.引用作为函数返回类型
#include <iostream>
#include <string>
using namespace std;
//返回值为引用类型
int & test2()
{
//int a = 29;
static int a = 29;//静态变量,存放在全局区,整个程序结束后系统自动释放
return a;
}
int main()
{
int &ref = test2();//定义引用类型接收 //自动转换int* const ref = &a
cout<<"ref : "<<ref<<endl;//ref :29
test2() = 89;//引用类型均可以作为左值,
cout<<"ref : "<<ref<<endl;//ref :89
return 0;
}
4.常量引用
#include <iostream>
#include <string>
using namespace std;
//利用 const 修饰引用,保证输入不改变
void test(const int & a)
{
//a = 10;//error C3892: “a”: 不能给常量赋值
cout<<"a : "<<a<<endl;
}
int main()
{
int a = 20;
test(a);
return 0;
}
const修饰引用其他作用
#include <iostream>
#include <string>
using namespace std;
int main()
{
int &ref = 10;//error C2440: “初始化”: 无法从“int”转换为“int &”
//const int &ref = 10; 加上const修饰可以,编译器自动优化代码,int temp = 10; int &ref = temp;
cout<<ref<<endl;// 10
return 0;
}
2807

被折叠的 条评论
为什么被折叠?



