【C++】reference parameter-引用参数

1.reference parameter

以下两个函数等效,只调用方式不同:

1>

 1 int reset(int i){
 2     i = 13;
 3     return i;
 4 }
 5 
 6 int main ()
 7 {
 8     int j=0;
 9     j = reset(j);
10     cout<<j<<endl;
11     system("PAUSE");
12   
13   return 0;
14 }

2>

 1 void reset(int &i){
 2     i = 13;
 3 }
 4 
 5 int main ()
 6 {
 7     int j;
 8     reset(j);
 9     cout<<j<<endl;
10     system("PAUSE");
11   
12   return 0;
13 }

函数区别,第一个必须要有返回值,第二个则不必.

调用时区别在第9行.

void reset()函数中引用参数 i 只是变量 j 的另一个名称,本质上就是变量 j ,不需要返回值,更改 i 的内容即等效于更改 j 的内容.

2.借引用参数实现一个函数返回多个结果

众所周知,一个函数只能有一个返回值。

但是借由reference parameter,可以实现返回多个结果的效果。

 1 //找出字符第一次出现位置pos,并得出共出现的次数occurs
 2 
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 string::size_type find_char(const string &s, char c, string::size_type &occurs){
 8     auto ret = s.size();
 9     occurs = 0;
10     for(decltype(ret) i = 0; i<s.size(); ++i){
11         if(s[i]==c){
12             if(ret == s.size()){
13                 ret = i;
14             }
15             ++occurs;
16         }
17     }
18     return ret;
19 }
20 
21 int main ()
22 {
23     string s = "casutxodoihsdfd"; 
24     string::size_type occurs= 0;
25     cout<<find_char(s,'d',pos)<<endl;
26     cout<<occurs<<endl;
27     system("PAUSE");
28     return 0;
29 }

输出

7
3

其中occurs就是作为被引用参数,在调用函数时其值被更改。

原文地址:https://www.cnblogs.com/liez/p/5481378.html