以下代码如何在 C++ 中工作?合乎逻辑吗?
How does the following code work in C++? Is it logical?
const int &ref = 9;
const int &another_ref = ref + 6;
为什么 C++ 允许常量引用的字面初始化,而非常量引用不允许?例如:
Why does C++ allow literal initialization for const references when the same is not permitted for non-const references? E.g.:
const int days_of_week = 7;
int &dof = days_of_week; //error: non const reference to a const object
这可以通过一个事实来解释,非常量引用可用于更改它所引用的变量的值.因此,C++ 不允许对 const 变量的非常量引用.
This can be explained by the fact that, a non-const reference can be used to change the value of the variable it is referring to. Hence, C++ does not permit a non-const reference to a const variable.
这是一个可能的解释吗?C++ 不允许:
Could this be a possible explanation? C++ does not allow:
int &ref = 7;
因为这不合逻辑,但是:
Because that is not logical, but:
const int &ref = 7;
几乎相当于:
const int val = 7;
所以常量变量允许字面初始化.
So literal initialization is permitted for const variables.
P.S.:我目前正在学习 Lippman 的 C++ Primer.
P.S.: I'm currently studying Lippman's C++ Primer.
所以你可以这样写代码:
So you can write code like this:
void f( const string & s ) {
}
f( "foobar" );
尽管严格来说,这里实际发生的并不是将文字绑定到 const 引用——而是创建了一个临时字符串对象:
Although strictly speaking what is actually happening here is not the literal being bound to a const reference - instead a temprary string object is created:
string( "foobar" );
并且这个无名字符串绑定到引用.
and this nameless string is bound to the reference.
请注意,像您这样做时创建非参数引用变量实际上很不寻常 - 引用的主要目的是用作函数参数和返回值.
Note that it is actually quite unusual to create non-parameter reference variables as you are doing - the main purpose of references is to serve as function parameters and return values.
这篇关于const 引用的字面初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!