"C + +" reference parameter-reference parameter

Source: Internet
Author: User

1.reference parameter

The following two functions are equivalent and are only called in a different way:

1>

1 int Reset (int i) {2     i =; 3     return} 5  6 int{8 int j=0; 9 j = Reset (j); COUT&L t;<j<<endl;11 System ("PAUSE"); return 0;       

2>

1 void Reset (int &i) {2     i =} 4  5 int{7     int Reset (j); 9 Cout<<j<<
          
           ENDL;10 System ("PAUSE"
           ); return 0;  
             

function differences, the first must have a return value, the second does not have to.

Called when the difference is in line 9th.

The void reset () function references parameter I just another name of the variable J, which is essentially the variable J, which does not require a return value, and changing the contents of I is equivalent to changing the contents of J.

2. Implementing a function With reference parameters returns multiple results

As we all know, a function can only have one return value.

However, the effect of returning multiple results can be achieved by reference parameter.

1 //find the first occurrence of a character Pos, and draw a total number of occurrences occurs2 3#include <iostream>4 5 using namespacestd;6 7 string:: Size_type Find_char (Const string&s,CharCstring:: Size_type &occurs) {8Auto ret =s.size ();9Occurs =0;Ten      for(Decltype (ret) i =0; I<s.size (); ++i) { One         if(s[i]==B) { A             if(ret = =s.size ()) { -RET =i; -             } the++occurs; -         } -     } -     returnret; + } -  + intMain () A { at     strings ="CASUTXODOIHSDFD";  -     string:: Size_type occurs=0; -Cout<<find_char (s),'D', POS) <<Endl; -cout<<occurs<<Endl; -System"PAUSE"); -     return 0; in}

Output

7 3

Where occurs is the referenced parameter, its value is changed when the function is called.

"C + +" reference parameter-reference parameter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.