Consider the following:
int ival = 1.01;
int &rval = 1.01; // error: non-const reference to a const value.
int &rval = ival;
rval = 1.01;
The first assignment of &rval to a literal value fails as expected. If I comment out that line the code compiles and runs. I understand why the initialization fails, but I'm confused why the assignment to rval works in the last line. I didn't think it was allowed to assign a reference to a literal value.
EDIT: Thanks for the quick answers. I'm tempted to delete this to hide my shame, but I think I'll leave it here so everyone else can point and laugh.
In my own defense, I'm working through the exercises in a book (C++ Primer) and this problem is about reference initialization. Still, it's pretty embarrassing to have so completely overlooked the point of a reference in the first place. :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…