![]() |
#2
tianxiao1102010-08-03 21:02
|

//带参数的构造函数
#include<iostream>
using namespace std;
class Box
{
public:
Box( int,int,int); //声明带参数的构造函数
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(12,25,30); //建立对象 box1,并指定 box1 长、宽、高的值
cout<<"The volume of box1 is "<<box1.volume( )<<endl;
Box box2(12,35,24); //建立对象 box2,并指定 box2 长、宽、高的值
cout<<"The volume of box2 is "<< box2.volume( )<<endl;
Box box3(123,234,256);
cout<<"The volume of box3 is "<<box3.volume( ) <<endl;
system("pause");
return 0;
}
/*
说明:不带参数的构造函数,在对数据成员初始化时,所有对象的初始化值都是相同的;为了使得不同对象得到不同的初始值,
必须使用带参数的构造函数。带参数的构造函数中的形参,其对应的实参在定义对象时给定。*/
为了加强记忆,只好用记笔记的这种笨办法。 #include<iostream>
using namespace std;
class Box
{
public:
Box( int,int,int); //声明带参数的构造函数
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(12,25,30); //建立对象 box1,并指定 box1 长、宽、高的值
cout<<"The volume of box1 is "<<box1.volume( )<<endl;
Box box2(12,35,24); //建立对象 box2,并指定 box2 长、宽、高的值
cout<<"The volume of box2 is "<< box2.volume( )<<endl;
Box box3(123,234,256);
cout<<"The volume of box3 is "<<box3.volume( ) <<endl;
system("pause");
return 0;
}
/*
说明:不带参数的构造函数,在对数据成员初始化时,所有对象的初始化值都是相同的;为了使得不同对象得到不同的初始值,
必须使用带参数的构造函数。带参数的构造函数中的形参,其对应的实参在定义对象时给定。*/