The ingenuity of dark horse programmers-reference

1. The meaning of reference and matters needing attention

#include <iostream>
using namespace std;
#include<string>
#include<ctime>
int main()
{
    int  a = 10;//a指向的内存值为10
    int& b = a;//引用的定义,b与a指向同一个内存;
    cout << &a << "&b: " << &b << endl;
    int c = 20;//c指向的内存值为20;
        b = c;//c指向的内存值赋值给b指向的内存值;
        cout << " a:" << a << " b: " << b << " C: " << c << endl;
    //引用注意事项:
    //1,引用必须初始化;2,引用一旦初始化就不能改变;

    system("pause");
    return 0;
} 

2. Reference function parameter passing

The actual parameter can be modified the same as the pointer passing. Advantage: simpler in form.

#include <iostream>
#include<string>
#include<ctime>
using namespace std;
void swap01(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
void swap02(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}
int main()
{
    int  a = 10;//a指向的内存值为10
    int b = 20;
    swap01(&a, &b);
    cout << "指针传递a:" << a << "指针传递b:" << b;
    swap02(a, b);
    cout << "引用传递a:" << a << "引用传递b:" << b;
    system("pause");
    return 0;
}

3. Note for the return value of a function: cannot return a reference to a local variable

#include <iostream>
#include<string>
#include<ctime>
using namespace std;
int& test01()
{
    int a = 10;
    return a;//不能返回局部变量的引用;
}
int& test02()
{
    static int a = 10;//static关键字,a变为静态常量;
    return a;
}
int main()
{
    int& ref1 = test01();
    cout << ref1 << endl;//正常打印,编译器做一次数值保留;
    cout << ref1 << endl;//ref指向的内存数据被释放,a不再为10
    int& ref2 = test02();
    cout << ref2 << endl;//正常打印
    cout << ref2<< endl;//正常打印
    system("pause");
    return 0;

4. The essence of reference: pointer constant

 5. Prevent the actual parameter value from being changed when the reference is passed as a function parameter:

Use const to modify formal parameters when passing parameters; the formal parameters are not allowed to be changed inside the function;

おすすめ

転載: blog.csdn.net/yyyllla/article/details/109328262