C++构造函数

构造函数用于解决类中的对象初始化的问题
构造函数是一类特殊的函数,与其他的成员函数不同的是构造函数构造函数不需要用户来调用它,而是建立对象的时候自动的执行

#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;
}

构造函数不需要用户调用,也不能够被用户调用。

带参数的构造函数

#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;
}

带参数的构造函数中的形参,其对应的实参在定义对象时给定。
使用带有参数的构造函数可以方便的实现对不同的对象进行初始化

#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;
}

猜你喜欢

转载自blog.csdn.net/yu132563/article/details/80038805