C++の一般参照
763 ワード
Reference to const
We can bind a reference to const to a nonconst object, a literal, or a more general expression:
The compiler transforms this code into something like:
In this case, rDval is bound to a temportary object.
We can bind a reference to const to a nonconst object, a literal, or a more general expression:
int i = 42;
const int &r1 = i; //bind a const int& to a plain int object
const int &r2 = 42; //ok.r1 is a reference to const
const int &r3 = r1 * 2; //ok.r3 is a reference to const
int &r4 = i * 1; //error.r4 is a plain,nonconst reference
double dval= 30;
const int &rDval = dval;
dval = 42;
cout << rDval << endl; // print 30
The compiler transforms this code into something like:
const int temp = dval;
const int &rDval = temp;
In this case, rDval is bound to a temportary object.