How does the following code work in C++? Is it logical?
const int &ref = 9;
const int &another_ref = ref + 6;
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
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.
Could this be a possible explanation? C++ does not allow:
int &ref = 7;
Because that is not logical, but:
const int &ref = 7;
Is almost equivalent to:
const int val = 7;
So literal initialization is permitted for const variables.
P.S.: I'm currently studying Lippman's C++ Primer.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…