解析C++中构造函数的默认参数和构造函数的重载
C++构造函数的默认参数 和普通函数一样,构造函数中参数的值既可以通过实参传递,也可以指定为某些默认值,即如果用户不指定实参值,编译系统就使形参取默认值。 【例】 #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; } 程序运行结果为: The volume of box1 is 1000 The volume of box2 is 1500 The volume of box3 is 4500 The volume of box4 is 9000 程序中对构造函数的定义(第12-16行)也可以改写成参数初始化表的形式: Box::Box(int h,int len):height(h),width(w),length(len){ } 可以看到,在构造函数中使用默认参数是方便而有效的,它提供了建立对象时的多种选择,它的作用相当于好几个重载的构造函数。 它的好处是,即使在调用构造函数时没有提供实参值,不仅不会出错,而且还确保按照默认的参数值对对象进行初始化。尤其在希望对每一个对象都有同样的初始化状况时用这种方法更为方便。 关于构造函数默认值的几点说明: C++构造函数的重载 通过下面的例子可以了解怎样应用构造函数的重载。 【例】定义两个构造函数,其中一个无参数,一个有参数。 #include <iostream> using namespace std; class Box { public : Box( ); //声明一个无参的构造函数 //声明一个有参的构造函数,用参数的初始化表对数据成员初始化 Box(int h,length(len){ } int volume( ); private : int height; int width; int length; }; Box::Box( ) //定义一个无参的构造函数 { height=10; width=10; length=10; } int Box::volume( ){ return (height*width*length); } int main( ) { Box box1; //建立对象box1,不指定实参 cout<<"The volume of box1 is "<<box1.volume( )<<endl; Box box2(15,25); //建立对象box2,指定3个实参 cout<<"The volume of box2 is "<<box2.volume( )<<endl; return 0; } 在本程序中定义了两个重载的构造函数,其实还可以定义其他重载构造函数,其原型声明可以为: Box::Box(int h); //有1个参数的构造函数 Box::Box(int h,int w); //有两个参数的构造函数
关于构造函数的重载的几点说明: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |