您的位置:首页 > 编程语言 > C语言/C++

C++构造函数初始化类对象

2019-04-12 15:53 519 查看

文章目录

一.构造函数

【1】构造函数不需要在定义时

声明类型

【2】构造函数不需要用户
进行调用

【3】可以在类内,也可以在类外构造函数;在类外构造函数时,需要在类内进行声明。
【4】构造函数的名字必须
与类名相同

【5】构造函数通常用于
对类内的数据进行初始化

二.构造函数的分类

  1. 无参
    的构造函数
  2. 有参
    的构造函数
  3. 参数初始化表
    的构造函数【重点】

三.构造函数的写法

  1. 无参的构造函数

eg1.从键盘输入时分秒,并输出时间。
思路:

  • 写一个
    Time
    类,公共数据由
    hour
    minute
    sec
    set_time
    函数和
    show_time
    函数组成,私有数据由,
    hour
    minute
    sec
    组成。
  • 写出两个函数
    set_time
    show_time
    函数还有主函数。
  • 在主函数建立
    对象
    进行调用。
#include<iostream>
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.set_time();
t2.show_time();
return 0;
}

以上代码是在类内构造函数,我们还可以在

类外构造函数
,但这也需要你在
类内进行声明函数

类外的函数写法:

Time::Time()
{
hour=0;
minute=0;
sec=0;
}

同时在类内的

pubilc
里加入:

Time();//函数声明

2.有参的构造函数
我们仍然用上面的例题作为分析:
对于有参数的构造函数我们需要做如下改动:

  • 声明构造函数的时候加入参数
Time(int,int,int);
  • 在类外定义带参数的构造函数
Time::Time(int h,int m,int s)
{
hour=h;
minute=m;
sec=s;
}
#include<iostream>
using namespace std;
class Time
{
public:
Time(int,int,int);void show_time();
private:
int hour;
int minute;
int sec;
};

Time::Time(int h,int minute;int sec)
{
hour=h;
minute=m;
sec=s;
}

void Time::show_time()
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main()
{
Time t1(12,25,30);
t1.show_time();
Time t2(15,30,21);
t2.show_time();
return 0;
}
  • 在建立对象之后进行函数调用的时候,可以
    直接赋值参数
Time t1(12,25,30);
t1.set_time();
t1.show_time();

3.参数初始化表构造函数
我们依然用如上的例子进行解释。
首先在原有基础上的有参构造函数声明上

	Time(int,int,int);

将其修改为:

Time(int h,int m,int s):hour(s),minute(m),sec(s);

当然主函数的对应调用函数依然不变。

#include<iostream>
using namespace std;
class Time
{
public:
Time(int h,int m,int s):hour(h),minute(m),sec(s);
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
void  Time::set_time()
{
cin>>hour>>minute>>sec;
}
void Time::show_time()
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main()
{
Time t1(12,25,30);
t1.set_time();
t1.show_time();return 0;
}

4.默认参数的构造函数

#include<iostream>
using namespace std;
class Time
{
public:
Time(int h=12,int m=25,int s=30);
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
Time::Time()
{
hour=h;
minute=m;
sec=s;
}
void  Time::set_time()
{
cin>>hour>>minute>>sec;
}
void Time::show_time()
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main()
{
Time t1;
t1.set_time();
t1.show_time();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: