第一篇:構(gòu)造函數(shù)的重載和用參數(shù)表對(duì)數(shù)據(jù)成員的初始化c++程序?qū)n}
#include
using namespace std;
class Box
{
public:
Box();//聲明一個(gè)無(wú)參的構(gòu)造函數(shù)
Box(int h,int w,int len):height(h),width(w),length(len){} 有參的構(gòu)造函數(shù)用參數(shù)的初始化表對(duì)其初始化
int volume();
void show_box();
private:
int height;
int width;
int length;
};
Box::Box()//定義一個(gè)無(wú)參的構(gòu)造函數(shù)
{
height=10;
width=10;
length=10;
}
void Box::show_box()
{
cout< cout< cout< } int Box::volume() { return(height*width*length); } int main() { Box box1; box1.show_box(); cout<<“the volume of box1 is”< box2.show_box(); cout<<“the volume of box2 is”< }//聲明一個(gè) #include using namespace std; class Box { public: Box(int,int,int);//聲明帶參數(shù)的構(gòu)造函數(shù)(參見(jiàn)之前的與BOX同名函數(shù)修改數(shù)值為某個(gè)固定數(shù)) int volume(); private: int height; int width; int length; }; Box::Box(int h,int w,int len) 函數(shù) { height=h; width=w; length=len; } int Box::volume() { return(height*width*length); } int main() { Box box1(12,23,34); box1的長(zhǎng)寬高 cout<<“the value of box1 is”< Box box2(23,34,45); cout<<“the value of box2 is”< return 0; } //在類外定義帶參數(shù)的的構(gòu)造//建立對(duì)象box1并指定第二篇:帶參數(shù)的構(gòu)造函數(shù)c++程序