为什么我可以在C ++中将现有引用分配给文字值? [英] Why can I assign an existing reference to a literal value in C++?

查看:92
本文介绍了为什么我可以在C ++中将现有引用分配给文字值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

int ival = 1.01;
int &rval = 1.01; // error: non-const reference to a const value.
int &rval = ival;

rval = 1.01;

第一次将& rval分配给文字值失败.如果我注释掉那行,代码将编译并运行.我知道为什么初始化失败,但是我很困惑为什么在最后一行中对rval的赋值有效.我认为不允许将引用分配给文字值.

The first assignment of &rval to a literal value fails as expected. If I comment out that line the code compiles and runs. I understand why the initialization fails, but I'm confused why the assignment to rval works in the last line. I didn't think it was allowed to assign a reference to a literal value.

编辑:感谢您的快速解答.我很想删除它以隐藏我的耻辱,但我想我会把它留在这里,以便其他所有人都可以指点并笑.

Thanks for the quick answers. I'm tempted to delete this to hide my shame, but I think I'll leave it here so everyone else can point and laugh.

在我自己的辩护中,我正在完成一本书(C ++ Primer)中的练习,而这个问题与参考初始化有关.仍然如此,一开始就完全忽略了参考点,这还是很尴尬的. :)

In my own defense, I'm working through the exercises in a book (C++ Primer) and this problem is about reference initialization. Still, it's pretty embarrassing to have so completely overlooked the point of a reference in the first place. :)

推荐答案

ival不是文字值,1.01是文字值.它已被复制到作为变量的ival中,绝对可以将其引用分配给另一个变量.

ival isn't a literal value, 1.01 is the literal value. It's been copied to ival which is a variable, which most definitely can have it's references assigned to another variable.

这篇关于为什么我可以在C ++中将现有引用分配给文字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆