![]() |
#2
rainbow12010-08-04 16:07
|

/*构造函数中参数的值既可以通过实参传递,也可以指定为某些默认值,
即如果用户不指定实参值,编译系统就使形参取默认值。*/
#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; //建立对象 box1 不指定实参
cout<<"The volume of box1 is "<<box1.volume( )<<endl;
Box box2(15); //只给定1个参数
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;
system("pause");
return 0;
}
/*
在构造函数中使用默认参数是方便而有效的,它提供了建立对象时的多种选择,它的作用相当于好几个重载的构造函数。它的好处是:
即使在调用构造函数时没有提供实参,不仅不会出错,而且还确保按照默认的参数值对对象进行初始化。尤其在希望对每一个对象都
有同样的初始化状况时用这种方法更为方便,不需输入数据,对象会按事先指定的值初始化。
没有给出实参的构造函数,是默认构造函数,全部参数都指定了默认值的构造函数也属于默认构造函数,一个类只能有一个默认构造函数*/
即如果用户不指定实参值,编译系统就使形参取默认值。*/
#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; //建立对象 box1 不指定实参
cout<<"The volume of box1 is "<<box1.volume( )<<endl;
Box box2(15); //只给定1个参数
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;
system("pause");
return 0;
}
/*
在构造函数中使用默认参数是方便而有效的,它提供了建立对象时的多种选择,它的作用相当于好几个重载的构造函数。它的好处是:
即使在调用构造函数时没有提供实参,不仅不会出错,而且还确保按照默认的参数值对对象进行初始化。尤其在希望对每一个对象都
有同样的初始化状况时用这种方法更为方便,不需输入数据,对象会按事先指定的值初始化。
没有给出实参的构造函数,是默认构造函数,全部参数都指定了默认值的构造函数也属于默认构造函数,一个类只能有一个默认构造函数*/