问题描述
今天遇见一个问题,即编写一个日期类 使得用户输入日期后 程序能输出下一天, 那么 如何使得计算后返回对象本身呢 ?
最后查资料得 利用this指针 返回对象本身的引用
##代码演示
class Date
{
private:
int m_year;
int m_month;
int m_day;
public:
Date(int year, int month, int day)
{
m_year = year;
m_month = month;
m_day = day;
}
void print_Date()
{
cout<<m_year<<"\t"<<m_month<<"\t"<<m_day<<endl;
}
Date& opra_next()
{
m_day++;
if (m_month == 12)
{
if (m_day > 31)
{
m_day = m_day % 31;
m_month++;
m_month = (m_month % 12);
}
}
else if (m_month == 1 || m_month == 3 || m_month == 5 || m_month == 7 || m_month == 10)
{
if (m_day > 31)
{
m_day = m_day % 31;
m_month++;
}
}
else if (m_month == 4 || m_month == 6 || m_month == 9 || m_month == 11)
{
if (m_day > 30)
{
m_day = m_day % 30;
m_month++;
}
}
else {
if (m_day > 28)
{
m_day = m_day % 28;
m_month++;
}
}
return *this;
}
};
int main()
{
int y, m, d;
cout << "please iput year month day" << endl;
cin >> y >> m >> d;
Date nextday(y, m, d);
nextday.opra_next();
nextday.print_Date();
system("pause");
return 0;
}