第一篇:構造函數的重載和用參數表對數據成員的初始化c++程序專題
#include
using namespace std;
class Box
{
public:
Box();//聲明一個無參的構造函數
Box(int h,int w,int len):height(h),width(w),length(len){} 有參的構造函數用參數的初始化表對其初始化
int volume();
void show_box();
private:
int height;
int width;
int length;
};
Box::Box()//定義一個無參的構造函數
{
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”< }//聲明一個 #include using namespace std; class Box { public: Box(int,int,int);//聲明帶參數的構造函數(參見之前的與BOX同名函數修改數值為某個固定數) 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,23,34); box1的長寬高 cout<<“the value of box1 is”< Box box2(23,34,45); cout<<“the value of box2 is”< return 0; } //在類外定義帶參數的的構造//建立對象box1并指定第二篇:帶參數的構造函數c++程序