在C ++中的参考初始化 [英] Reference initialization in C++
问题描述
任何人都可以向我解释为什么这两个语句之间有区别。
Can anybody explain to me why there is a difference between these two statements?
class A{};
const A& a = A(); // correct
A& b = A(); // wrong
它说
类型<$ c的非const引用的无效初始化$ c> A& 从 A
c $ c> const 这里?
Why does const
matter here?
推荐答案
非const引用必须初始化为l-值。如果你可以用临时数来初始化它们,那么下面是什么?
Non-const references must be initialised with l-values. If you could initialise them with temporaries, then what would the following do?
int& foo = 5;
foo = 6; // ?!
const
延长裁判员的生命,因为他们是 const
,没有可能性,你会尝试修改不在内存中的东西。例如:
const
references have the special property that they extend the life of the referee, and since they are const
, there is no possibility that you'll try to modify something that doesn't sit in memory. For example:
const int& foo = 5;
foo = 6; // not allowed, because foo is const.
请记住,引用实际上必须引用某些东西,而不仅仅是临时变量。例如,以下内容有效:
Remember that references actually have to refer to something, not just temporary variables. For example, the following is valid:
int foo = 5;
int& bar = foo;
bar = 6;
assert(foo == 6);
这篇关于在C ++中的参考初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!