Notes for reading C++ Primer 4/e.
Reference
nonconst reference can only reference to the same nonconst object.
int incr(int val) {
return ++val;
}
int incrRef(int &val) {
return ++val;
}
int incrRefConst(const int &val) {
cout << val << endl;
return val;
}
int main() {
short v1 = 0;
const int v2 = 42;
double v4 = 3.4;
int v3 = incr(v1);
v3 = incrRef(v1);
v3 = incrRefConst(v1);
int v5 = incr(v4);
v5 = incrRef(v4);
v5 = incrRefConst(v4);
cout << v4 << " " << v5 << endl;
return 0;
}
[note]:
- nonconst refernce parameter 的彈性較低,不能以 const object 初始化,也不能以字面常數 (ex. 42, 'a', "Hello", 3.14...) 或 rvalue 做為 argument.