c++对c的拓展_函数的引用

注意:1、引用可作为形参较指针更为直观 2可作为返回值 (判断标准:空间是否释放)

#include <iostream>

#include <stdlib.h>

using namespace std;

void change(int & x,int & y){    //当引用作为形参时 调用者直接传变量名 而指针作为形参时 实参要取地址才可改变数值

int temp =x;

x=y;

y=x;

}

void test(){

int a=10 ,b=20;

change(a,b);

cout << a<< " "<<b<<endl;

}

void create(int *&q){   //若使用指针则需要使用二级指针作为形参 实参也需取地址 开辟空间时用*q接收

q=(int *)malloc(sizeof(int)*5);  

}

void test02(){

int * p=null;

create(p);

}

int& test03(){

int a=0;

return a;

}

int main(){

test();

test02();

test03()=10; // 不能返回局部变量 调用以后空间释放 判断是否能返回看空间是否释放

}

结果:20 10

 

posted @ 2022-04-05 22:13  spking  阅读(43)  评论(0)    收藏  举报