栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 基础知识-引用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 基础知识-引用

c++ 基础知识-引用

引用的本质是指针常量

1.引用基础
#include   
#include   
using namespace std;

int main()
{
	int a =10;
	int c = 15;
	int &b = a;//引用必须初始化
	//int &b = c;// “b”: 重定义;多次初始化,引用只能初始化依次,不可以更改
	cout<<"a = "<#include   
#include   
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 : "< 
3.引用作为函数返回类型 
#include   
#include   
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 : "< 
4.常量引用 
#include   
#include   
using namespace std;

//利用 const 修饰引用,保证输入不改变
void  test(const int & a)
{
	//a = 10;//error C3892: “a”: 不能给常量赋值
	cout<<"a : "<
	int a  = 20;
	test(a);
	return 0;
}  

const修饰引用其他作用

#include   
#include   
using namespace std;
int main()
{
	int &ref = 10;//error C2440: “初始化”: 无法从“int”转换为“int &”
	//const int &ref = 10; 加上const修饰可以,编译器自动优化代码,int temp = 10;  int &ref = temp;
	cout<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/865004.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号