【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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值