函数返回值是const或者const引用
来源:互联网 发布:淘宝质量好的童装店 编辑:程序博客网 时间:2024/06/01 08:09
const表明一个值是不可更改的,我一直试图了解如下语句中,const的作用
const int & getInt();int & getInt();二者的差距在于前者的返回值是个右值,后者的返回值是个左值。也就是说,前者返回后只能赋值给其他变量(因为它被const修饰了,也就是说这个这个变量所指向的内存是不能被更改的),而后者可以称为赋值的对象。
对此,我写了如下一个程序段:
int & getInt(int &n){ return n;}int main(){ int n=1; int a = getInt(n); a++; cout<<n<<endl; cout<<a<<endl; return 0;}
对于这段程序,你预期的结果是什么?答案是:n=1a=2把上面程序做一个小小的修改:
int & getInt(int &n){ return n; } int main() { int n=1; int& a = getInt(n); a++; cout<<n<<endl; cout<<a<<endl; return 0;}
输出是n=2a=2
这里涉及到函数返回值的定义了。
通俗点来说吧,函数的返回值大部分情况是是返回的一个右值,也就是说你在函数的外面是要这么干的:type name=fuction(....)。也就是说函数外面你声明的变量(也可以说是接住函数返回值的变量)一定是和函数返回值类型相同的或者可以由返回值类型转化而成的类型。这么一说的话,以上两段程序也就不难理解了,因为
int a=2;int &b=a;int c=b;是合法的,一个引用变量(此处为b)赋值给一个普通变量是合法的,所以一个int &类型的返回值赋值给int类型是合理的,只不过从此之后a和n(第一段程序)就天各一方,没有任何关系了,如果此时把a声明int &a,那么a还是指向的n那块内存,所以两个变量还是一条绳子上的蚂蚱。
当然,一种特殊的情况还是要记住的,const &可以返回一个左值!
- 函数返回值是const或者const引用
- C++ const函数返回值必须为const引用
- C++ const函数返回值必须为const引用
- 函数返回const指针与const引用。
- 函数返回的临时对象为const类型,const引用
- 关于函数返回引用和const对象
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数
- const参数,const返回值与const函数 .
- c++ const: const 变量, const 输入参数, const 返回值, const 成员函数
- 海量存储系列之序言—之一—之二—之三
- 时间类运算符重载
- spring几种事务配置@以及spring所需jar包
- 根据数据表导入xls数据
- JS关闭chrome标签
- 函数返回值是const或者const引用
- Spring的注入方式都是什么?如何选用?
- 错误 1 error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- 汇编学习历程(键盘中断劫持)
- 热身运动——简单工厂模式
- 可重复组合的应用 By ACReaper
- SNMP++: Transport is not supported
- 帝国下载整合disucz 2.0 会员积分同步教程
- Struts2拦截器—自定义拦截器验证用户登录