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

C++:引用

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

C++:引用

引用的使用说明
  • 基本使用
  • 注意事项
  • 引用做函数参数
  • 引用作函数的返回值
  • 引用的本质
  • 常量引用

基本使用

作用:给变量起别名
语法:数据类型 &别名 =原名 (有点类似指针的感觉)

#include 
#include 
#include //c++中字符串需要添加这个头文件
using namespace std;

int main()
{
	int a = 88;
	int &b = a;
	cout << a << endl;
	cout << b << endl;

	b = 20;
	cout << a << endl;
	cout << b << endl;
	system("pause");
	return 0;
}

注意事项

1.引用必须初始化
2.初始化之后就不可被改变了

#include 
#include 
#include //c++中字符串需要添加这个头文件
using namespace std;

int main()
{
	int a = 88;
	int &b = a;
	int &c;
	system("pause");
	return 0;
}

引用做函数参数

作用:函数传参数时,可以利用引用的技术让形参修饰实参
有点:可以简化指针修改实参

#include 
#include 
#include //c++中字符串需要添加这个头文件
using namespace std;

void swap1(int, int);
void swap2(int *, int *);
void swap3(int &, int &);
int main()
{
	int a = 22, b = 33;
	cout << "未修改:" << "a=" << a << " " << "b=" << b << endl;

	swap1(a, b);
	cout << "普通交换:" << "a=" << a << " " << "b=" << b << endl;
	swap2(&a, &b);
	cout << "指针交换:" << "a=" << a << " " << "b=" << b << endl;
	swap3(a, b);
	cout << "引用交换:" << "a=" << a << " " << "b=" << b << endl;

	system("pause");
	return 0;
}

void swap1(int x, int y)
{
	int temp = x;
	x = y;
	y = temp;
}
void swap2(int *x, int *y)
{
	int temp = *x;
	*x = *y;
	*y = temp;
}
void swap3(int &x, int &y)
{
	int temp = x;
	x = y;
	y = temp;
}

引用作函数的返回值
  • 不要返回局部变量
  • 函数的调用可以作为左值
    第一次正确,是因为编译器做了保留

    Static变量是在全局区 等待程序运行完后才会释放

    函数的返回是一个引用 那么函数可以作为一个左值
引用的本质

本质:引用的本质在C++内部实现是一个指针常量
指针常量 int * const p:指向不可以修改 指针指向的值可以修改
C++推荐使用引用计数 因为语法简单

常量引用

作用:修饰形参 防止误操作

#include 
#include 
#include //c++中字符串需要添加这个头文件
using namespace std;

void show(int & c)
{
	c = 100;
	cout << c << endl;
}

int main()
{
	int a = 10;

	show(a);
	cout << a << endl;
	system("pause");
	return 0;
}
输出结果都是100

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/835556.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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