use*_*997 1 c++ const reference
这是我现在const string&无法解决的问题:为什么可以分配到nonconst变量并进一步修改?
const string& shorter_s(const string &s1, const string &s2) {
return s1.size() < s2.size() ? s1 : s2;
}
int main() {
const string s1 = "longer", s2 = "short";
string result = shorter_s(s1, s2);
cout << result << endl;
result += "++";
cout << result << endl;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
short
short++
Run Code Online (Sandbox Code Playgroud)
是不是result要引用const string s2对象,不能通过添加来修改"++"?
string result = shorter_s(s1, s2);
Run Code Online (Sandbox Code Playgroud)
因为result不是参考.函数调用的结果被赋值给一个值变量,这意味着它被复制了.result不引用s2因为它不引用任何变量,因为它不是引用.
如果你想让它引用某个东西然后把它作为参考,你会发现你不能把它作为一个可变的参考:
string& result = shorter_s(s1, s2); // doesn't compile
const string& result = shorter_s(s1, s2); // OK
Run Code Online (Sandbox Code Playgroud)