博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++ 10-引用(变量、常量、函数)code sample
阅读量:3576 次
发布时间:2019-05-20

本文共 1432 字,大约阅读时间需要 4 分钟。

语法: 数据类型 &别名 = 原名

本质: 在c++内部实现是一个指针常量

一、变量

引用必须初始化

引用在初始化后,不可以改变

#include 
#include
#include
using namespace std;int main(int argc, char const *argv[]){ int a = 10; int b = 20; //int &c; //错误,引用必须初始化 int &c = a; //一旦初始化后,就不可以更改 c = b; //这是赋值操作,不是更改引用,将a的值更改为b;指针为int * p = &a; *p = b; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; system("pause"); return 0;}

二、常量

常量引用主要用来修饰形参,防止误操作;在函数形参列表中,可以加const修饰形参,防止形参改变实参

#include 
#include
#include
using namespace std;//引用使用的场景,通常用来修饰形参void showValue(const int& v) { //v += 10; //const修饰的变量,指向v的内存地址,其值无法被改变; cout << v << endl;}int main(int argc, char const *argv[]){ const int& ref = 10; //ref = 100; //加入const后不可以修改变量 cout << ref << endl; //函数中利用常量引用防止误操作修改实参 int a = 10; showValue(a); system("pause"); return 0;}

 三、函数引用

code sample 在  的test04函数里有实现;简单说其作用类似指针;

作用:引用是可以作为函数的返回值存在的

注意:不要返回局部变量引用

用法:函数调用作为左值

//返回局部变量引用int& test01() {	int a = 10; //局部变量	return a;}//返回静态变量引用int& test02() {	static int a = 20;	return a;}int main() {	//不能返回局部变量的引用	int& ref = test01();	cout << "ref = " << ref << endl;	cout << "ref = " << ref << endl;	//如果函数做左值,那么必须返回引用	int& ref2 = test02();	cout << "ref2 = " << ref2 << endl;	cout << "ref2 = " << ref2 << endl;	test02() = 1000;	cout << "ref2 = " << ref2 << endl;	cout << "ref2 = " << ref2 << endl;	system("pause");	return 0;}

转载地址:http://ouagj.baihongyu.com/

你可能感兴趣的文章
小甲鱼Python第十七讲(Python的乐高积木)
查看>>
小甲鱼Python第十九讲(函数,我的地盘听我的)
查看>>
小甲鱼python第二十讲(内嵌函数和闭包)
查看>>
小甲鱼Python第二十一讲(lambda表达式)
查看>>
小甲鱼Python第二十三讲、第二十四讲(递归-这帮小兔崽子、汉诺塔)
查看>>
小甲鱼Python第二十七讲(集合)
查看>>
可调谐半导体激光器的窄线宽测试及压缩
查看>>
matlab中 %d,%f,%c,%s
查看>>
常见的光纤接头汇总
查看>>
半导体激光器—问题整理(二)
查看>>
科研日记7.31
查看>>
zemax仿真二向色镜
查看>>
stm32单片机编程时extern的用法
查看>>
UART4和5的问题
查看>>
Spring框架中在并发访问时的线程安全性
查看>>
网站部署
查看>>
什么情况下会发生栈内存溢出。
查看>>
何为去中心化
查看>>
缓存一致性:写策略
查看>>
Cache一致性:MESI
查看>>