【发布时间】:2014-01-31 20:58:07
【问题描述】:
我正在尝试在一个类中制作一个程序,并在每个类中添加一个。 所以如果日期是:2014 年 1 月 1 日,我希望它是 2015 年 2 月 2 日。
我能够计算出日期和月份的部分,但是由于某种原因,我得到了一个奇怪的年份数字。
当我尝试调试程序时,我发现它正在打印以下内容
1/1/2014
1/1/2014
1/0/2014 // I am not sure why did it change the day to 0 but I don't care about this as I'm getting the correct result at the end
2/2/4028 // I am more concern about the 4028 ! I don't know from where did this come from
2/2/4028
这是我到目前为止所做的:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Date
{
public:
int day, year, monthnum;
Date(int d=1, int m2 =1, int y= 2014)
{
monthnum = m2;
day = d;
year =y;
cout << *this; // this is just for testing purposes
}
Date operator+(const Date&) const;
friend ostream& operator << (ostream& out, const Date& date)
{
out << date.monthnum << "/" << date.day << "/" << date.year <<endl;
return out;
}
};
Date Date:: operator+(const Date& date) const
{
return Date(day+date.day,monthnum+ date.monthnum ,date.year+year); // I think there is something with the "date.year + year" because when I remove this I get my initialization of the year which is 2014, however, I need it to be 2015 when I add one to it.
}
void testprogram()
{
Date date1(1), date2(1), date3(0);
date3 = date1 + date2;
cout << date3 << endl;
}
int main()
{
testprogram();
return 0;
}
【问题讨论】:
-
顺便说一句,创建自己的日期和时间类并不容易,尤其是在处理闰年时。除非您出于教育目的这样做,否则我建议您找到并学习如何使用体面的第 3 部分库(EG boost::Date_Time)
-
是的,我这样做是为了教育目的。你建议如何处理闰年?
-
我自己没有研究过,但是你可以从stackoverflow.com/questions/725098/leap-year-calculation开始。在日期计算中有很多“If this or that”类型的情况。尤其是你们中的一些人可以追溯到足够远的历史,并在实际的日历中遇到根本性的变化