我正在尝试在一个类中创建一个程序,并在每个类中添加一个日期。
因此,如果日期为: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;
}
最佳答案
请仔细考虑Date
代表什么,以及向Date
添加内容意味着什么。 Date
是一个特定的时间点。将它们加在一起就像将丹佛和克利夫兰的经度和纬度加在一起,并期望坐标意味着有用的东西!
您的默认参数将年份指定为2014,因此当您添加date1和date2时,您将获得date3.year = 2014 +2014。我提醒您避免使用默认参数,除非在 call 者几乎总是需要默认参数的情况下。它也使您无法使用date3,因为您指定的是day = 0,monthnum = 1,year = 2014。