C + + Reference

Source: Internet
Author: User

  • Reference
    • --& Reference character
    • The reference must be initialized
    • Once initialized, it will not change its point to
  • Use
    • As a function parameter--does not take up extra space, can improve the function execution efficiency
      • #include <iostream>usingStd::endl;usingstd::cout;//reference functions as parametersvoidSwapintAintb//parameters are passed in the same way that the value is passed--and the copy is{//initial taxiing parameter: int a = x;int B = y;    inttemp =A; A=b; b=temp;}//x/Y values are not exchanged//address Passing-value passingvoidSwaq (int*PA,int*pb) {    inttemp = *PA; *PA = *PB; *PB =temp;}//Address Delivery//Reference Delivery//Benefits: No extra space to increase execution efficiencyvoidSwal (int& Ref1,int&Ref2) {//Parameter initialization: int & ref1 = a;int & ref2 = b;    inttemp =ref1; REF1=Ref2; Ref2=temp;}intMain () {intx =Ten; inty = -; cout<<"x ="<< x <<Endl; cout<<"y ="<< y <<Endl; Swap (x, y);//actual Parameterscout <<"after the Exchange"<<Endl; cout<<"x ="<< x<<Endl; cout<<"y ="<<y<<Endl; Swaq (&x,&y);//actual Parameterscout <<"after the Exchange"<<Endl; cout<<"x ="<< x <<Endl; cout<<"y ="<< y <<Endl; Swal (x, y);//actual Parameterscout <<"after the Exchange"<<Endl; cout<<"x ="<<x<<Endl; cout<<"y ="<<y<<Endl; System ("Pause"); return 0;}

        • Reference can be used as the return value of a function
            • When the return statement is not copied, it returns the variable itself
            • #include <iostream>usingStd::endl;usingstd::cout;intarr[5] = {0,1,2,3,4 };int& Func (intidx) {    returnarr[idx];}intMain () {func (0) =Ten; cout<< arr[0] <<Endl; System ("Pause"); return 0;}

C + + Reference

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.