带参数的构造函数及使用默认参数的构造函数

来源:互联网 发布:java 将图片写入word 编辑:程序博客网 时间:2024/05/17 22:51

带参数的构造函数:

#include<iostream>using namespace std;class Box{   public:      Box(int h=10,int w=10,int l=10);//使用有参的构造函数对类中数据初始化,即设定默认值      int volume();   private:      int height;      int width;      int length;};Box::Box(int h,int w,int l){   height=h;   width=w;   length=l;}int Box::volume(){   return (height*width*length);}int main(){   Box box1;//无参对象对应无参构造函数 ,数据使用默认值    cout<<"the volume1 is "<<box1.volume()<<endl;   Box box2(12);   cout<<"the volume2 is "<<box2.volume()<<endl;   Box box3(12,23);   cout<<"the volume3 is "<<box3.volume()<<endl;   Box box4(12,23,34);   cout<<"the volume4 is "<<box4.volume()<<endl;   system("pause");   return 0;}
使用默认参数的构造函数:

#include<iostream>using namespace std;class Box{   public:      Box(int h,int w,int l);      int volume();   private:      int height;      int width;      int length;};Box::Box(int h,int w,int l){   height=h;   width=w;   length=l;}int Box::volume(){   return (height*width*length);}int main(){   Box box1(12,23,34);//此处使用构造函数,有参对象,对应有参构造函数    cout<<"the new volume is "<<box1.volume()<<endl;   system("pause");   return 0;}