加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 引用类型返回函数和后缀增量

发布时间:2020-12-16 09:46:45 所属栏目:百科 来源:网络整理
导读:我正在读 the Wikipedia page about references. 它包含以下代码: int preinc(int x) { return ++x; // "return x++;" would have been wrong}preinc(y) = 5; // same as ++y,y = 5 我确实尝试使用return x进行编译;而不是返回x;.正如预测的那样,这导致了以
我正在读 the Wikipedia page about references.

它包含以下代码:

int& preinc(int& x) 
{ 
    return ++x;  // "return x++;" would have been wrong
}

preinc(y) = 5; // same as ++y,y = 5

我确实尝试使用return x进行编译;而不是返回x;.正如预测的那样,这导致了以下错误:

error: invalid initialization of non-const reference of type ‘int&’
from a temporary of type ‘int’

我不明白这个错误.我有一种模糊的直觉,即x的增量发生得太晚(即,在preinc的函数调用结束后).但是,我不知道这是一个什么问题,因为变量x永远不会存在.欢迎任何解释.

解决方法

错误的原因是post increment x返回一个临时值,这不能绑定到非const左值引用.这是同一问题的简化版本:

int i = 42;
int& j = i++; // Error: i++ returns temporary value,then increments i.
const int& k = i++; // OK,const reference can bind to temporary.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读