1】带默认形参的函数
}
C++
允许在函数
说明
或函数
定义
中为形参预赋一个默认值;
}
在调用带有默认参数值的函数时:
}
若指定实参,形参则使用实参的值;
}
否则,形参使用默认值。
}
如:
int sub(int x=8,int y=3)
{ return x-y;}
int main()
{
sub(20,15); //
传递给形参
x
,
y
的值是
20
和
15
sub(10); //
传递给形参
x
,
y
的值是
10
和
3
sub(); //
形参
x
,
y
使用默认值
8
和
3
}
}
使用带有默认形参值的函数时应注意:
}
(1)
定义默认形参值时必须自右向左连续定义;(函数调用时,参数由右向左入栈)
}
int f(int a , float b=3.0, char c=
‘
h
’
, int d=0); //
正确
}
int f(int a , float b=3.0, char c , int d=0); //
错误
}
(2)
调用函数时,如果省去了某个实参,则这个实参直到最右端的实参都要省去;
}
(3)
默认形参值的说明必须出现在函数调用之前;
}
(4)
在同一个作用域内,一旦定义了默认形参值,就不能再定义它;
}
(5)
不同的作用域,可以提供不同的默认形参值;
}
(6)
在函数说明给出形参的默认值时,形参名可以省略;
}
int f(int , float =3.0 , char =
“
h
”
, int =0);
2】使用默认形参的函数容易产生二义性
如:
#include <iostream>
using namespace std;
using namespace std;
class Clock{
private:
int H,M,S;
public:
Clock() //
{
cout<<"constructor1:"<<endl;
}
Clock(int h,int m=0,int s=0)
{
H = h, M = m, S = s;
cout<<"constructor:"<<H<<":"<<M<<":"<<S<<endl;
}
private:
int H,M,S;
public:
Clock() //
{
cout<<"constructor1:"<<endl;
}
Clock(int h,int m=0,int s=0)
{
H = h, M = m, S = s;
cout<<"constructor:"<<H<<":"<<M<<":"<<S<<endl;
}
Clock(Clock& p)
{
cout<<"copy constructor,before call:"<<H<<":"<<M<<":"<<S<<endl;
H = p.H;
M = p.M;
S = p.S;
}
{
cout<<"copy constructor,before call:"<<H<<":"<<M<<":"<<S<<endl;
H = p.H;
M = p.M;
S = p.S;
}
~Clock()
{
cout<<"destructor:"<<H<<":"<<M<<":"<<S<<endl;
}
{
cout<<"destructor:"<<H<<":"<<M<<":"<<S<<endl;
}
void SetTime(int h,int m,int s)
{
H=(h>=0 && h<24)?h:0;
M=(m>=0 && m<60)?m:0;
S=(s=0 && s<24)?s:0;
}
void ShowTime()
{
cout<<H<<":"<<M<<":"<<S<<endl;
}
};
{
H=(h>=0 && h<24)?h:0;
M=(m>=0 && m<60)?m:0;
S=(s=0 && s<24)?s:0;
}
void ShowTime()
{
cout<<H<<":"<<M<<":"<<S<<endl;
}
};
Clock fun(Clock c)
{
return c;
}
{
return c;
}
int main()
{
Clock c1(8,0,0);
Clock c2; // 编译器将不知道才c2用使用那个构造函数,因为此时Clock(8,0,0),Clock(8,0),Clock()都是等价的
return 0;
}
{
Clock c1(8,0,0);
Clock c2; // 编译器将不知道才c2用使用那个构造函数,因为此时Clock(8,0,0),Clock(8,0),Clock()都是等价的
return 0;
}