0
点赞
收藏
分享

微信扫一扫

C++基础知识 - const常量引用

转角一扇门 2022-01-30 阅读 50

const常量引用

  • 在 C++中可以声明 const 引用
  • 语法: const Type& name = var;
  • const 引用让变量拥有只读属性

分两种情况:
1.用变量初始化常引用
2.用字面量初始化常量引用

#include <iostream>
#include <Windows.h>

using namespace std;

int main(void) {
	int a = 20;
	//1.用变量初始化常引用
	const int& b = a;

	//b = 100;		//常引用是让变量引用变成只读,不能通过引用对变量进行修 改

	//2.用字面常量初始化常引用
	const int& c = 10;	//这个是在 C++中,编译器会对这样的定义的引用分 配内存,这算是一个特例

	//c = 100;		//	不能修改

	system("pause");
	return 0;
}
举报

相关推荐

0 条评论