const引用

在C++中可以声明const引用

const Type& name = var;

const引用让变量拥有只读属性

const int &a = b
const int &a = 10;


Case1:

<pre name="code" class="cpp">#include <iostream>
using namespace std;

//常引用的知识架构
int main()
{
	//普通引用

	int  a = 10;
	int &b = a;
	printf("b:%d \n", b);

	//常引用
	int  x = 20;
	const int &y = x;  //常引用 是 让变量 引用只读属性 不能通过y去修改x了
	//y = 21;

	//常引用 初始化 分为2种情况
	//1> 用变量 初始化 常引用
	{
		int x1 = 30;
		const int &y1 = x1; //用x1变量去初始化 常引用
	}
	//2> 用字面量 初始化 常量引用
	{
		const int a = 40;  //c++编译器把a放在符号表中
		int &m = 41; //普通引用 引用一个字面量 请问字面量有没有内存地址
		//引用 就是给内存取多个门牌号 (多个别名)
		//printf("&40:%d \n", &40);
		const int &m = 43;  //c++编译器 会 分配内存空间 
	}
	cout<<"hello..."<<endl;
	system("pause");
	return 0;
}
 
 

Case2

struct Teacher
{
	char name[64];
	int age ;
};


//void printTeacher(const Teacher  * const myt)
void printTeacher(const Teacher &myt)
{
	//常引用 让 实参变量 拥有只读属性 
	//myt.age = 33;
	printf("myt.age:%d \n", myt.age);
	
}

int main()
{
	Teacher  t1;
	t1.age = 36;

	printTeacher(t1);

	
	cout<<"hello..."<<endl;
	system("pause");
	return 0;
}

 const引用结论 

1)Const &int e  相当于 const int * conste

2)普通引用相当于 int *const e1

3)当使用常量(字面量)对const引用进行初始化时,C++编译器会为常量值分配空间,并将引用名作为这段空间的别名

4)使用字面量对const引用初始化后,将生成一个只读变量



转载于:https://www.cnblogs.com/zhangyaoqi/p/4591635.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值