C++ 函数的缺省参数

来源:互联网 发布:电子元件查询软件 app 编辑:程序博客网 时间:2024/06/03 16:39

一、普通函数的缺省参数

# include<iostream>using namespace std;void func(int m=0,int n=1)//m=0,叫做函数的默认参数,也叫做缺省参数。缺省参数可以有一个,也可以有多个。{cout<<"m:"<<m<<"\t"<<"n:"<<n<<endl;}int main(){func();func(3,5);//函数调用时,没有参数时,就会调用缺省参数;如果有参数时,以参数为准。return 0;}

运行结果:


二、成员函数的缺省参数

# include<iostream>using namespace std;class A{public:void set(int =20,int =3);//这样写也是允许的。void count(bool=false);private:int w;int h;};int main(){A a;cout<<"使用缺省函数时:"<<endl;a.set();a.count();a.count(true);cout<<endl<<"重新复制时:"<<endl;a.set(5,2);    a.count();a.count(true);//这样缺省函数也实现了函数的重载。return 0;}void A::set(int width,int height){w=width;h=height;}void A::count(bool val){if(val==true){cout<<"val值为真时:"<<w*h<<endl;}elsecout<<"val值为假时:"<<w*h/2<<endl;}

运行结果:


注释:

1、重载函数使用方便,易于理解。默认参数的函数如果不加标注的话,很容易被忽略,而且容易被有参的同名函数覆盖。

2、具有默认参数的函数重载的是参数的数值,而重载函数重载的是参数的类型。

0 0
原创粉丝点击