C++Study

本文详细介绍了C++中的引用概念,包括其作为变量别名的特性,初始化要求,以及引用与常量结合的常引用。引用不占用额外内存,且一旦绑定不能改变。文中还展示了引用在函数参数传递中的优势,特别是在交换函数Swap中的应用,并探讨了常引用如何确保变量不可变。

引用

即意为着给已有的变量取别名。

int x = 1000;
int& y = x;//&紧跟着数据类型
cout << x << endl;//1000
cout << y << endl;//1000
//printf("%d",y);

引用并没有开辟新的空间,只是对原来的变量取了一个新的别名。
注意事项:
1.引用在定义时必须初始化,要明确是给哪一个已有变量取别名。
2.一个已有变量可以有多个引用,即多个别名。
3.一个引用只能指向一个实体。
引用的应用:

Swap(int& ra,int& rb)
{
	int temp = ra;
	ra = rb;
	rb = temp;
}
int main()
{
	int a = 10, b = 90;
	Swap(a, b);//直接传引用
	return;
}

引用做参数。Swap中其实也是一个例子。还有就是学习链表的时候,有二级指针的应用,这里就可以变化为一级指针的引用。

常引用

const int x = 10;
int& y = x;//报错

const关键字锁定x无法更改,引用y成功那么不是可以更改x了?所有应该给引用也加上const关键字:

const int x = 10;
const int& y = x;

当然,如果x没有const修饰,可是你想让y无法更改x,也可以在引用前加上const修饰

int x =10;
const int& y = x;

这就是常引用。

#include <iostream> int main() { std::cout << "Hello MinGW!" << std::endl; return 0; }正在启动生成... cmd /c chcp 65001>nul && D:\gongzuo\minGW\mingw64\bin\gcc.exe -fdiagnostics-color=always -g D:\gongzuo\c++study\study1.cc -o D:\gongzuo\c++study\study1.exe C:\Users\hcl\AppData\Local\Temp\ccs5wWxN.o: In function `main': D:/gongzuo/c++study/study1.cc:3: undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)' D:/gongzuo/c++study/study1.cc:3: undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))' C:\Users\hcl\AppData\Local\Temp\ccs5wWxN.o: In function `__tcf_0': D:/gongzuo/minGW/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/iostream:74: undefined reference to `std::ios_base::Init::~Init()' C:\Users\hcl\AppData\Local\Temp\ccs5wWxN.o: In function `__static_initialization_and_destruction_0': D:/gongzuo/minGW/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/iostream:74: undefined reference to `std::ios_base::Init::Init()' C:\Users\hcl\AppData\Local\Temp\ccs5wWxN.o:study1.cc:(.rdata$.refptr._ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_[.refptr._ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_]+0x0): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' C:\Users\hcl\AppData\Local\Temp\ccs5wWxN.o:study1.cc:(.rdata$.refptr._ZSt4cout[.refptr._ZSt4cout]+0x0): undefined reference to `std::cout' collect2.exe: error: ld returned 1 exit status
07-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值