类和对象:数据成员之使用默认参数初始化


当创建对象不给定参数时,去掉括号如:Date date0


#include <iostream>

using namespace std;

class Date
{
    int day, month, year;
public:
    Date(int yy = 1949, int mm = 0, int dd = 0);
    void myprint();
};
Date::Date(int yy, int mm, int dd):year(yy),month(mm),day(dd){}
void Date::myprint()
{
    cout<<year<<"-"<<month<<"-"<<day<<endl;
}

int main()
{
    Date date0, date1(2015), date2(2015,3), date3(2015,3,26);
    //当创建对象不给定参数时,去掉括号,如:Date date0;
    cout<<"date0: ";
    date0.myprint();
    cout<<"date1: ";
    date1.myprint();
    cout<<"date2: ";
    date2.myprint();
    cout<<"date3: ";
    date3.myprint();
    return 0;
}