C++委托構造函數
C++11新标準擴充了構造函數初始值的功能,使得我們可以定義所謂的委托構造函數(delegating constructor)。一個委托構造函數使用它所屬類的其他構造函數執行它自己的初始化過程,或者說它把它自己的一些職責(或者全部)職責委托給了其他構造函數。
和其他構造函數一樣,一個委托構造函數也有一個成員初始值的清單和一個函數體。
#include<iostream>
using namespace std;
class Date
{
public:
//非委托構造函數使用對應的實參初始化成員
Date(int year,int month,int day):_year(year), _month(month), _day(day)
{
cout << "正在調用非委托構造函數Date(int year,int month,int day)!"
<< endl << endl;
}
Date(int month,int day):Date(2019,month,day)
{
cout << "正在調用Date(int month,int day)委托構造函數!" << endl << endl;
}
Date(int day):Date(2019,11,day)
{
cout << "正在調用Date(int day)委托構造函數!" << endl <<endl;
}
friend ostream &operator<<(ostream &os, Date const date1)
{
return os << "year = " << date1._year << endl <<"month = " << date1._month<< endl << " day = " << date1._day <<endl;
}
private:
int _year;
int _month;
int _day;
};
void FunTest()
{
Date d(3);
cout << d;
cout << "==============================================" << endl;
Date a(1997,10,16);
cout << a;
cout << "==============================================" << endl;
Date t(11,15);
cout << t;
}
int main()
{
FunTest();
system("pause");
return 0;
}
結果如下:
