您的位置:首页 > 其它

构造函数的具体使用

2016-03-12 22:32 190 查看
构造函数来处理对象的初始化,是一种特殊的成员函数,不需要用户来调用它,而是建立对象时自动执行。名字必须要与类名相同,不具有任何类型,

不返回任何值。

1.带参数的构造函数:构造函数名(参数形参1,参数形参2,。。。。。)

实参是在定义对象是给出的,定义对象一般为:类名 对象名(实参1,实参2,。。。)

#include<iostream>

using namespace std;

class Box

{

public:
Box(int ,int,int); 
int voulune();

private:
int height;
int wide;
int length;

};

Box::Box(int h,int w,int len)

{
height=h;
wide=w;
length=len;

}

int Box::voulune()

{
return(height*wide*length);

}

int main()

{
Box box(12,13,15);
cout<<"The voulune of box is"<<box.voulune();
return 0;

}

2.用参数初始化表对数据成员初始化:即在原来函数首部的尾部加一个冒号,然后列出参数的初始化表;

#include<iostream>

using namespace std;

class Box

{

public:
Box();
Box(int h,int w,int len):height(h),wide(w),length(len){};
int voulune();

private:
int height;
int wide;
int length;

};

Box::Box()

{
height=10;
wide=10;
length=10;

}

int Box::voulune()

{
return(height*wide*length);

}

int main()

{
Box box;
cout<<"The voulune of box is"<<box.voulune();
return 0;

}

3.调用函数时不必给出实参的构造函数,称为默认构造函数(类中只能有一个默认构造函数),如果用户不指定实参值,就会取形参默认值

例如:

#include<iostream>

using namespace std;

class Box

{

public:
Box(int h=10,int w=10,int len=10);//
int voulune();

private:
int height;
int wide;
int length;

};

Box::Box(int h,int w,int len)

{
height=h;
wide=w;
length=len;

}

int Box::voulune()

{
return(height*wide*length);

}

int main()

{
Box box;
cout<<"The voulune of box is"<<box.voulune();
return 0;

}

在构造函数中使用默认参数是方便有效的,提供了建立对象时的多种选择,相当于好几个重载的构造函数。

在一个类中定义了全部是默认的构造函数后,不能再定义重载构造函数。避免出现歧义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: