c++中函数的引用

函数中的引用
引用可以作为函数的形参
不能返回局部变量的引用
#include
#include
using namespace std;
//形参是引用
void swap(int *x, int *y)//*x *y表示对x y取地址
{
    int tmp = *x;
    *x = *y;
    *y = tmp;
}
void test01()
{
    int a = 10;
    int b = 20;
    swap(&a, &b);
    cout << a << "  " << b << endl;
}
void swap_ref(int &x,int &y)//取别名int &x = a; int &y = b;
{
    int tmp = x;
    x = y;
    y = tmp;
}
void test02()
{
    int a = 10;
    int b = 20;
    swap_ref(a, b);
    cout << a << "  " << b << endl;
}
//形参是指针引用
void get_mem(int **q) {
    *q = (int *)malloc(5 * sizeof(int));
}
void get_mem_ref(int * &q) 
{
    q = (int *)malloc(5 * sizeof(int));
}
void test03()
{
    int *p = NULL;
    get_mem(&p);
    get_mem_ref(p);

}
int main()
{
    test01();
    test02();
    test03();
    return 0;
}

你可能感兴趣的:(c++,开发语言)