【c++】参数传递—const形参与实参

【c++】参数传递—const形参与实参,第1张

1、const是什么

const是c++中常用的类型修饰符,主要用于定义常量与指针,主要有两种类型:

顶层const:const修饰的部分是标识符直接代表的对象

const int i = 0;

底层const:const修饰的部分是标识符间接代表的对象(如指针)

const int* a = &i;

其他const修饰例子(判断是什么类型的const可以看修饰的东西是否由标识符直接表示)

int *const pi = &i;            //pi是顶层const,修饰的是指针pi
const int *const ci = &i;      //ci既是顶层也是底层const

如果函数无需改变引用形参的值,最好将其声明成常量引用。

2、const形参与实参

直接看例子:

函数实参无定义const实参有定义const形参在函数体中实参结果值
int demo(int i)可输入可输入可改变不会改变
int demo(const int i)可输入可输入不可改变不会改变
int demop(int* a)可输入不可输入可改变不会改变
int demop(const int *a)可输入可输入不可改变不会改变
int demop(int* const a)可输入不可输入可改变不会改变
void demox(int &p)可输入可输入可改变可改变
void demox(const int &p)可输入可输入不可改变不会改变

参考文献:https://blog.csdn.net/xiaokunzhang/article/details/80977375

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

原文地址: http://outofmemory.cn/langs/727584.html

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

发表评论

登录后才能评论

评论列表(0条)

保存