Constructor is used to solve the problem of object initialization in a class.
Constructor is a special kind of function. Unlike other member functions, the constructor does not need to be called by the user, but is automatically executed when an object is created.
#include <iostream>
//#include "student.h"
//#include <string>
//#include <cstring>
using namespace std;
class Time
{ public:
Time() //构造函数必须与类的名称相同
{ //利用构造函数对对象中的数据成员进行初始化
hour=0;
minute=0;
sec=0;
}
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
void Time::set_time() {
cin>>hour;
cin>>minute;
cin>>sec;
}
void Time::show_time() {
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main() {
Time t1;
t1.set_time();
t1.show_time();
Time t2;
t2.show_time();
return 0;
}
The constructor does not need to be called by the user and cannot be called by the user.
Constructor with parameters
#include <iostream>
//#include "student.h"
//#include <string>
//#include <cstring>
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;
}
int Box::volume() {
return height*width*length;
}
int main() {
Box box1(12,25,36); //建立对象box1并且指定对象的长宽高
cout<<"the voluime of box1 is"<<box1.volume()<<endl;
Box box2(15,65,32);
cout <<"the volume of box2 is"<<box2.volume()<<endl;
return 0;
}
Formal parameters in a constructor with parameters whose corresponding actual parameters are given when the object is defined.
Using the constructor with parameters can be convenient to initialize different objects .
#include <iostream>
//#include "student.h"
//#include <string>
//#include <cstring>
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=5;
width=8;
length=23;
}
int Box::volume() {
return height*width*length;
}
int main() {
Box box1; //建立对象box1并且指定对象的长宽高
cout<<"the voluime of box1 is"<<box1.volume()<<endl;
Box box2(15,65,32);
cout <<"the volume of box2 is"<<box2.volume()<<endl;
return 0;
}