c++ 基础知识-引用

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;
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值