C ++ --- cited references do function parameter, returns the constant references

Explanation

Equivalent to a reference to the object from a new name.
Usage is simple:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a = 10;
    int &b = a;

    cout<<b<<endl;

    return 0;
}

result:
Here Insert Picture Description

Precautions

1, reference must be initialized
Unlike initialize variables, when the definition of reference, and the program will reference objects it references are bound together, not a simple assignment, initialization is complete references, and it has been the object it references bound together, can no longer operate as an assignment as bound with other objects
2, reference must match the type
as in the example above, a is an integer, then the references can not be other types
such as:
Here Insert Picture Description
wrong
3, references initialization value must be an object, the value is not
as
Here Insert Picture Description

it's wrong

const reference

As the name suggests, is a reference to the constant

#include <iostream>
#include <string>
using namespace std;

int main()
{
    const int a = 20;
    const int &b = a;

    cout<<b<<endl;

    return 0;
}

Note: After herein by reference, not by modifying the value of a b is
another use:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a = 20;
    const int &b = a;
    
    cout<<b<<endl;

    return 0;
}

Here again, changes can not operate a b, but may be modified by other means a normal

References Do Function Parameters


#include <iostream>
#include <string>
using namespace std;

void myswap(int &a, int &b)
{
    int tmp;
    tmp=a;
    a=b;
    b=tmp;
}

int main()
{
    int a = 20, b = 10;
    myswap(a,b);
    cout<<"a:"<<a<<'\t'<<"b:"<<b<<endl;

    return 0;
}

The output
Here Insert Picture Description
action where a pointer is equivalent, can be modified by a reference parameter argument

The function returns a reference to do

usage

#include <iostream>
#include <string>
using namespace std;

int a = 10;
int& example()
{
    return a;
}

int main()
{
    int &b = example();//使用一个引用类型来接收引用类型的返回值
    cout<<b<<endl;
    return 0;
}

However, we can not return a reference to a local variable
, such as
Here Insert Picture Description
where a is the local variables, references do not return to it. Since the end of the current function, a variable memory will be freed, if the function ends, the address operation is also illegal operation is not allowed.

Published 14 original articles · won praise 30 · views 8732

Guess you like

Origin blog.csdn.net/weixin_43086497/article/details/104905564