【发布时间】:2013-01-10 05:57:32
【问题描述】:
可能重复:
C++: How do I decide if to pass params by ref or by value?
以下函数是从C++ Primer, 5th Edition 第 211 页和第 214 页编写的。此函数将返回给定字符在字符串中第一次出现的位置,并告知该字符在该字符串中出现的次数。
string::size_type find_char(const string &s, char c, string::size_type &occurs)
{
// Compares the given character with string
// Records the first occurrence of that character
// The change in &occurs is reflected back to the original variable
}
作者建议在传递参数时使用“References to Avoid Copies”,对于函数不会更改的参数,建议使用“constreference parameters”。 他们为什么不将char c 设为const 参考参数?
【问题讨论】:
-
您可能想查看其他一些关于此的帖子,例如 stackoverflow.com/questions/9442202/… 。其中一些相当不错。我特别喜欢这个:stackoverflow.com/questions/2139224/…
标签: c++ parameters constants pass-by-reference