2010-4-14
来源:互联网 发布:windows修改网络命令 编辑:程序博客网 时间:2024/04/29 12:06
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;
}
- 2010-4-14
- 2010年4月14日总结
- 2010年4月14日星期三
- 2010-4-19到2010-5-14实习总结
- 2010-4
- 2010-1-14
- 2010-01-14
- 2010-01-14
- 2010-02-14
- 2010-03-14
- 2010-04-14
- 2010-05-14
- 2010-7-14日志
- 2010/7/14
- 2010-08-14
- 2010-08-14(周六)
- 2010-9-14
- 2010/9/14
- WINCE声音驱动模型概述(3)--放音的消息解析
- 设计模式-Interpreter模式戏说
- linux wait函数解析
- 设计模式_可复用面向对象软件的基础- 观后感
- 鸡兔同笼问题
- 2010-4-14
- 我等你... 可是现在我连等的资格都没有了, 对不起, 打扰了
- WINCE声音驱动模型概述(4)
- 准备写技术博客了
- 声明和定义
- 菜鸟感言
- SharePoint2010 create custom list definition(SharePoint基于custom content type创建list definition)
- 开始了
- 触发器初步认识