1、函数参数缺省值
#include<iostream>
using namespace std;
void fun(int a=12,char b='d')//全部指定
{
cout << a << ' ' << b << endl;
}
void fun1(int a,char b='d',float f=124.123)//部分指定,从右到左,连续指定
{
cout << a << ' ' << b << ' ' << f << endl;
}
int main()
{
//函数调用,有默认值的参数,可以不用传递实参
fun();
//函数调用,没有默认值的参数,必须传递实参
fun1(123);
//有实参,传递实参会覆盖掉默认值
fun(12, 's');
system("pause");
return 0;
}
2、函数重载
函数相同,函数参数类型或个数不同,
#include<iostream>
using namespace std;
void fun(int a)
{
cout << "1:" << a << endl;
}
void fun(char b)
{
cout << "2:" << b<< endl;
}
void fun(char str[])
{
cout << "5:" <<str<< endl;
}
void fun(float c,int f)
{
cout << "3.1:" <<c <<"3.2: "<<f<< endl;
}
void fun(char d,int e)
{
cout << "4.1:" << d <<"4.2" <<e<< endl;
}
int main()
{
char str[10] = "sjdhj";
fun(str);//传递字符数组
fun(12);//C++中 根据输入的实参类型、数目自动识别所需函数。
system("pause");
return 0;
}
*返回值不能作为函数重载的条件。