c++构造函数重载

来源:互联网 发布:苹果软件更新不了 编辑:程序博客网 时间:2024/06/10 03:51
#include <iostream>  
using namespace std;  
class Box  
{public : Box( ); //声明一个无参的构造函数
Box(int h,int w,int len):height(h),width(w),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,30,25); //建立对象box2,指定3个实参
cout<<"The volume of box2 is "<<box2.volume( )<<endl;
return 0;
  }