您的位置:首页 > 编程语言 > C语言/C++

转】C++默认参数与函数重载

2012-03-08 19:43 211 查看
转载自 赵扶风
在C++中,可以为参数指定默认值。在函数调用时没有指定与形参相对应的实参时, 就自动使用默认参数。

默认参数的语法与使用:

注意:

如:int mal(int a, int b=3, int c=6, int d=8) 正确,按从右到左顺序设定默认值。

int mal(int a=6, int b=3, int c=5, int d) 错误,未按照从右到左设定默认值。c设定缺省值了,而其右边的d没有缺省值。

如:void mal(int a, int b=3, int c=5); //默认参数

mal(3, 8, 9 ); //调用时有指定参数,则不使用默认参数

mal(3, 5); //调用时只指定两个参数,按从左到右顺序调用,相当于mal(3,5,5);

mal(3); //调用时只指定1个参数,按从左到右顺序调用,相当于mal(5,3,5);

mal( ); //错误,因为a没有默认值

mal(3, , 9) //错误,应按从左到右顺序逐个调用

再如: void mal(int a=8, int b=3, int c=5); //默认参数

mal( ); //正确,调用所有默认参数,相当于mal(8,3,5);

在相同的声明域中,函数名相同,而参数表不同。通过函数的参数表而唯一标识并且来区分函数的一种特殊的函数用法。

例:


#include <iostream>


using namespace std;


int test(int a,int b);


float test(float a,float b);


void main()




...{


cout << test(1,2) << endl << test(2.1f,3.14f) << endl;


cin.get();


}




int test(int a,int b)




...{


return a+b;


}




float test(float a,float b)




...{


return a+b;


}



1、参数类型不同的例子:

(1)

#include<iostream.h>

void Add(char x,char y)

{cout<<"字符串是:";

cout<<x<<y<<endl;

}

void Add(int x,int y)

{cout<<"两数的和是: ";

cout<<x+y<<endl;

}

void main()

{

Add('O','k');

Add(65,100);

}
(2)重载函数abs(),求int、float和double类型数据的绝对值。

#include <iostream.h>

//求int型数据的绝对值

int abs(int x)

{

if (x<0) x=-x;

return x;

}

//求float型数据的绝对值

float abs(float x)

{

if (x<0) x=-x;

return x;

}

//求 double型数据的绝对值

//仿照上面的函数编写

//主函数

void main()

{

int a=-357;

float b=63.85;

double c=-6974.26;

cout<<abs(a)<<'\t'<<abs(b)<<'\t'<<abs(c)<<endl;
2、参数个数不同的例子:求2~4个整数当中的最大值,根据参数个数的不同调用不同的max()函数

#include<iostream.h>

int max(int x,int y)

{

if(x>y) return x;

else return y;

}

int max(int x,int y,int z)

{

int a=max(x,y);

return max(a,z);

}

int max(int a,int b,int c,int d)

{

//自行编制这部分代码

}

main()

{

cout<<max(1,2)<<endl;

cout<<max(1,2,3)<<endl;

cout<<max(1,2,3,4)<<endl;

}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: