和普通函数一样,构造函数中参数的值既可以通过实参传递,也可以指定为某些默认值,即如果用户不指定实参值,编译系统就使形参取默认值。
例9.3的问题也可以使用包含默认参数的构造函数来处理。
【例9.4】将例9.3程序中的构造函数改用含默认值的参数,长、宽、高的默认值均为10。
- #include <iostream>
- using namespace std;
- class Box
- {
- public :
- Box(int h=10,int w=10,int len=10); //在声明构造函数时指定默认参数
- int volume( );
- private :
- int height;
- int width;
- int length;
- };
- Box::Box(int h,int w,int len) //在定义函数时可以不指定默认参数
- {
- height=h;
- width=w;
- length=len;
- }
- int Box::volume( )
- {
- return (height*width*length);
- }
- int main( )
- {
- Box box1; //没有给实参
- cout<<"The volume of box1 is "<<box1.volume( )<<endl;
- Box box2(15); //只给定一个实参
- cout<<"The volume of box2 is "<<box2.volume( )<<endl;
- Box box3(15,30); //只给定2个实参
- cout<<"The volume of box3 is "<<box3.volume( )<<endl;
- Box box4(15,30,20); //给定3个实参
- cout<<"The volume of box4 is "<<box4.volume( )<<endl;
- return 0;
- }
程序运行结果为:
程序中对构造函数的定义(第12-16行)也可以改写成参数初始化表的形式:
Box::Box(int h,int w,int len):height(h),width(w),length(len){ }
可以看到,在构造函数中使用默认参数是方便而有效的,它提供了建立对象时的多种选择,它的作用相当于好几个重载的构造函数。
它的好处是,即使在调用构造函数时没有提供实参值,不仅不会出错,而且还确保按照默认的参数值对对象进行初始化。尤其在希望对每一个对象都有同样的初始化状况时用这种方法更为方便。
关于构造函数默认值的几点说明: