1、定义:在基于对象的程序中,在定义一个对象时,也需要作初始化的工作,即对数据成员赋初值。因为不能再类声明中对数据成员初始化【类并不是一个实体,而是一个抽象类型,并不占用存储空间,显然无法容纳数据】,C++提供了构造函数来处理对象的初始化。构造函数是一种特殊的成员函数,与其他成员函数不同,不需要用户来调用它,而是再建立对象时自动执行【用户只需再定义对象的同时制定数据成员的初值即可】。
2、特点:构造函数的名字不许与类名相同,而不能任意命名,以便编译系统能识别它,并把它作为构造函数来处理。它不具备任何类型,不返回任何值。
3、示例:用构造函数为对象的数据成员赋初值
#include <iostream>
using namespace std;
class Time
{
public:
Time()
{
hour=0;
minutes=0;
sec=0;
}
void set_time();
void show_time();
private:
int hour;
int minutes;
int sec;
};
void Time::set_time(){
cin>>hour;
cin>>minutes;
cin>>sec;
}
void Time::show_time(){
cout<<hour<<":"<<minutes<<":"<<sec<<endl;
}
int main()
{
Time t1;
t1.set_time();
t1.show_time();
Time t2;
t2.show_time();
return 0;
}
程序结果如图:
执行主函数时,首先建立对象t1,此时自动执行构造函数Time。在执行构造函数Time过程中对t1对象的数据成员赋初值为0。然后在执行主函数中的t1.set_time()函数。
示例二:带参数的构造函数
#include <iostream>
using namespace std;
class Box
{
public:
Box(int,int,int);
int volume();
private:
int height;
int width;
int length;
};
Box::Box(int h,int w,int len){
height=h;
width=w;
length=len;
}
//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(15,25,30);
cout<<"the volume of box1 is "<<box1.volume()<<endl;
Box box2(15,30,21);
cout<<"the volume of box2 is "<<box2.volume()<<endl;
return 0;
}
3、用参数初始化表对数据成员初始化
//Box::Box(int h,int w,int len):height(h),width(w),length(len){}
4、构造函数的重载
#include <iostream>
using namespace std;
class Box
{
public:
Box();
Box(int h,int w,int len):height(h),width(w),length(len){}
int volume();
private:
int height;
int width;
int length;
};
Box::Box(){
height=10;
width=10;
length=10;
}
int Box::volume(){
return (height*width*length);
}
int main()
{
Box box1;
cout<<"the volume of box1 is "<<box1.volume()<<endl;
Box box2(15,30,25);
cout<<"the volume of box2 is" <<box2.volume()<<endl;
cout << "Hello world!" << endl;
return 0;
}
程序结果如图: