int main() { 建立对象boxl,不指定实参 Box box1; cout<<"The volume of boxl is int Box:volume( "<<box1.volume()<<endl; B0xb0x2(15,30,25); return(height*width cout<<"The volume of box2 is *length); "<<box2.volume()<<endl; return 0; 建立对象box2. 指定3个实参 还可以定义 Box:Box(int h); 其他重载构 造函数 Box:Box(int h,int w);
int main( ) { Box box1; cout<<″The volume of box1 is ″<<box1.volume( )<<endl; Box box2(15,30,25); cout<<″The volume of box2 is ″<<box2.volume( )<<endl; return 0; } int Box∷volume( ) { return(height*width *length); } 建立对象box1,不指定实参 建立对象box2, 指定3个实参 还可以定义 其他重载构 造函数 Box∷Box(int h,int w); Box∷Box(int h);
说明: ()调用构造函数时不必给出实参的构造函数,称 为默认构造函数(default constructor). 无参的构造函数属于默认构造函数。一个类只能 有一个默认构造函数。 (2)如果在建立对象时选用的是无参构造函数,应 注意正确书写定义对象的语句。 (3)尽管在一个类中可以包含多个构造函数,但是 对于每一个对象来说,建立对象时只执行其中一个 构造函数,并非每个构造函数都被执行。 冠
(3) 尽管在一个类中可以包含多个构造函数,但是 对于每一个对象来说,建立对象时只执行其中一个 构造函数,并非每个构造函数都被执行。 说明: (1) 调用构造函数时不必给出实参的构造函数,称 为默认构造函数(default constructor)。 无参的构造函数属于默认构造函数。一个类只能 有一个默认构造函数。 (2) 如果在建立对象时选用的是无参构造函数,应 注意正确书写定义对象的语句
9.1.6使用默认参数的构造函数 构造函数中参数的值既可以通过实参传递,也 可以指定为某些默认值,即如果用户不指定实 参值,编译系统就使形参取默认值。 例9.4将例9.3程序中的构造函数改用含默认值的 参数,长、宽、高的默认值均为10。 在例9.3程序的基础上改写如下:
9.1.6 使用默认参数的构造函数 例9.4 将例9.3程序中的构造函数改用含默认值的 参数,长、宽、高的默认值均为10。 在例9.3程序的基础上改写如下: 构造函数中参数的值既可以通过实参传递,也 可以指定为某些默认值,即如果用户不指定实 参值,编译系统就使形参取默认值
#include <iostream> int Box:volume( using namespace std, 在声明构造 return(height*width*length): 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; 造函数
#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()szendl; Box box2(15) 只给定2个实参 cout<<"The volume of box2 is "<<box2.volume()<endl; 给定3个实参 Box box3(15,30)片 cout<<"The volume of box3 is "<<box3.volume()<<endl; 程序运行结果为 B0xb0x4(15,30,20)片 The volume of box1 is 1000 cout<<"The volume of box4 is The volume of box2 is 1500 "<<box4.volume()<<endl; The volume of box3 is 4500 return 0; The volume of box4 is 9000
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); cout<<″The volume of box3 is ″<<box3.volume( )<<endl; Box box4(15,30,20); cout<<″The volume of box4 is ″<<box4.volume( )<<endl; return 0; } 没有给实参 只给定一个实参 只给定2个实参 给定3个实参 程序运行结果为 The volume of box1 is 1000 The volume of box2 is 1500 The volume of box3 is 4500 The volume of box4 is 9000