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); // X: no matching function for call to 'incrRef'
v3 = incrRefConst(v1); // 0
int v5 = incr(v4);
v5 = incrRef(v4); // X: no matching function for call to 'incrRef'
v5 = incrRefConst(v4); // 3
cout << v4 << " " << v5 << endl; // 3.4 3
return 0;
}
[note]:
- nonconst refernce parameter 的彈性較低,不能以 const object 初始化,也不能以字面常數 (ex. 42, 'a', "Hello", 3.14...) 或 rvalue 做為 argument.
No comments:
Post a Comment