类与对象之初始化列表


​ 在此前的代码中,我们在构造函数体中使用赋值语句初始化对象的数据成员,还可以用另一种方式——初始化列表

格式:构造函数():属性1(值1)属性2(值2)…{}

#include<iostream>
using namespace std;
class CDate
{
int Date_Year, Date_Month, Date_Day;
public:
CDate(int y = 2000, int m = 1, int d = 1);
void Display();

};
#include "l3_08.h"
//传统初始化
//CDate::CDate(int y, int m, int d)
//{
// cout << "Excuting constructor...\n";
// Date_Day = d;
// Date_Month = m;
// Date_Year = y;
//}
//初始化列表
CDate::CDate(int y, int m, int d):Date_Year(y),Date_Month(m),Date_Day(d)
{
cout << "Excuting constructor...\n";
}
void CDate::Display()
{
cout << Date_Year << "-" << Date_Month << "-" << Date_Day << endl;
}
#include "l3_08.h"
int main()
{
// 定义一个CDate对象initiateday,使用默认构造函数初始化
CDate initiateday;
// 定义一个CDate对象newday,使用带年份参数的构造函数初始化
CDate newday(2019);
// 定义一个CDate对象today,使用带年、月、日参数的构造函数初始化
CDate today(2019, 3, 9);
// 输出initiateday的日期信息
cout << "Inintiateday is:";
initiateday.Display();
// 输出newday的日期信息
cout << "Newday is:";
newday.Display();
// 输出today的日期信息
cout << "Today is:";
today.Display();
return 0;

}

Author: T1g3r
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source T1g3r !
评论
  TOC