先看一段代码 函数
int test(int &i) {return i;} int main() { cout<<test(1)<<endl; return 0; }此时编译会报错,提示“initial value of reference to non-const must be an lvalue” ,也即传递给非const引用的值必需要为左值
而若是改为 spa
int test(const int &i) {return i;} int main() { cout<<test(1)<<endl; return 0; }程序就能正确执行。
综上,若是形参是non-const引用,则实参必须是non-const型的变量,要想能给函数传递具体的数值或字符串,则可将形参设为const类型。
code