C++:引用

C++:引用,第1张

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

基本使用

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

#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

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/741104.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-28
下一篇2022-04-28

发表评论

登录后才能评论

评论列表(0条)

    保存