关于默认构造函数的尝试

来源:互联网 发布:数据库round down函数 编辑:程序博客网 时间:2024/05/18 03:58

代码:

/**

*时间:2013/1/24

*功能:使用默认参数的构造函数

*目的:试验默认构造函数

*/

 

#include <iostream>

using namespace std;

 

class Box

{    

       private:

              intheight;

              intwidth;

              intlength;

       public:

              Box(inth = 10,int w = 10,int len = 10);              //在声明构造函数时指定默认参数

              intvolume();

};

 

Box::Box(int h,int w,int len)                //在定义函数时可以不指定默认参数

{

       height= h;

       width= w;

       length= len;

}

 

int Box::volume()

{

       return(height*width*length);

}

 

int main()

{

       Boxbox1;                                                //没有给实参

       cout<< "The volume of box1 is " << box1.volume() <<endl;

       Boxbox2(15);                                          //只给定一个实参

       cout<< "The volume of box2 is " << box2.volume() <<endl;

       Boxbox3(15,30);                               //只给定两个实参

       cout<< "The volume of box3 is " << box3.volume() <<endl;

       Boxbox4(15,30,20);                                 //给定三个实参

       cout<< "The volume of box4 is " << box4.volume() <<endl;

       return0;

}

运行结果:

 

小结:

1.给定默认参数的构造函数,调用时参数可不完全给出,即没有指明的参数会自动调用之前设置的默认参数

原创粉丝点击