[英]can anyone please explain me the need for & in the first code snippet
In the following snippet of code I have noticed ampersand is used even though we aren't manipulating the string.在下面的代码片段中,我注意到即使我们没有操作字符串,也使用了&符号。 Can anyone please tell me why it's needed?
谁能告诉我为什么需要它?
bool compare(string &s1,string &s2)
{
return s1.size() < s2.size();
}
Snippet 2: would this code work?片段 2:这段代码能用吗?
bool compare(string s1,string s2)
{
return s1.size() < s2.size();
}
The &
sign (reference) is needed, because this way the program will only use a reference to the original string. &
符号(引用)是必需的,因为这样程序将只使用对原始字符串的引用。 If you don't use a reference, then the program will copy the string, so the program will be如果不使用引用,那么程序将复制字符串,因此程序将
A const reference ( const string&
) is even better, because it will make it read-only, so you can pass string literals. const 引用(
const string&
)甚至更好,因为它将使其成为只读,因此您可以传递字符串文字。 Like compare("abc", "foo bar")
.像
compare("abc", "foo bar")
。
Yes, your second snippet would work, but it's not recommended.是的,您的第二个片段会起作用,但不建议这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.