Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

assigning char to int reference and const int reference in C++

I noticed that assigning a char to a const int& compiles, but assigning it to a int& gives a compilation error.

char c;
int& x = c;    // this fails to compile
const int& y = c;    // this is ok

I understand that it is not a good practice to do this, but I am curious to know the reason why it happens.

I have searched for an answer by looking for "assigning to reference of different type", "assigning char to a int reference", and "difference between const reference and non-const reference", and came across a number of useful posts (int vs const int& , Weird behaviour when assigning a char to a int variable , Convert char to int in C and C++ , Difference between reference and const reference as function parameter?), but they do not seem to be addressing my question.

My apologies if this has been already answered before.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
int& x = c;

Here an implicit conversion from char to int is being performed by the compiler. The resulting temporary int can only be bound to a const reference. Binding to a const int& will also extend the lifetime of the temporary result to match that of the reference it is bound to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...