問題描述
以下代碼如何在 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" );
盡管嚴格來說,這里實際發(fā)生的并不是將文字綁定到 const 引用——而是創(chuàng)建了一個臨時字符串對象:
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.
請注意,像您這樣做時創(chuàng)建非參數(shù)引用變量實際上很不尋常 - 引用的主要目的是用作函數(shù)參數(shù)和返回值.
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模板網(wǎng)!