int height,width,length;
};
int Box::volume()
{
return height*width*length;
}
int main()
{
Box box1;
cout<<box1.volume()<<endl;
Box box2(15);
cout<<box2.volume()<<endl;
Box box3(15,20);
cout<<box3.volume()<<endl;
Box box4(15,20,30);
cout<<box4.volume()<<endl;
}
在构造函数中使用默认参数是方便有效的,这相当于提供了多个重载的构造函数。
说明:
(1)构造函数的默认值要在声明中指定。
(2)声明时可以省略形参名,如:Box(int=10,int=10,int=10);
(3)当构造函数的参数全部指定为默认值时,可以给出一个或多个参数,也可以不给参
数,这时就不能再定义重载构造函数了。
//补充实例
#include<iostream>
#include<iomanip>
using namespace std;
//----------------------------------
class Date{
int year, month, day;
public:
Date(int y=2000,int m=1,int d=1); //构造函数 1,有三个参数,设置默认参数
Date(const string& s); //构造函数 2,有一个参数,无默认参数
bool isLeapYear()const;
void print()const;
};//-------------------------------
Date::Date(int y,int m,int d){
year=y; month=m; day=d;
}//--------------------------------
Date::Date(const string& s){
year=atoi(s.substr(0,4).c_str()); //取出子串转换为字符串再转换为整型
month=atoi(s.substr(5,2).c_str());
day=atoi(s.substr(8,2).c_str());
}//--------------------------------