C++的构造函数

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

程序结果如图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值