C ++函数中的新增功能(按引用调用,按值调用,返回引用,默认参数)
函数调用:通过引用调用
我们已经在C语言中了解到,函数调用有两种类型:1)按值调用。2)按址调用。
C++引入了按引用调用的概念,它使我们能够按引用将参数传递给函数。当我们通过引用传递参数时,被调用函数中的格式参数将成为调用函数中实际参数的别名,这意味着当函数使用其自己的参数时,它实际上正在处理原始数据。
语法
//声明
return_type function_name( type_of_argument,type_of_argument,..);
//打电话
function_name(&actual_argument,&actual_argument,..);
//定义
return_type function_name(type_of_argument &alias_variable,..)
{
....;
}例子
//程序使用CALL BY REFERENCE交换两个值
#include <iostream>
using namespace std;
//函数声明
void swap(int&,int&);
int main(){
int a=10,b=20;
cout<<"\nVALUES BEFORE SWAPPING :\n";
cout<<"A:"<< a<<",B:"<< b;
//函数调用
swap(a,b);
cout<<"\nVALUES AFTER SWAPPING :\n";
cout<<"A:"<< a<<",B:"<< b;
cout<<"\n";
return 0;
}
//函数定义
void swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}VALUES BEFORE SWAPPING : A:10,B:20 VALUES AFTER SWAPPING : A:20,B:10