使用类在c ++中添加year实现

rul*_*ing 2 c++ class

我正在尝试在一个类中创建一个程序并添加到每个日期中的一个.因此,如果日期是: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
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所做的:

      #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;
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ard 5

仔细考虑Date代表什么,以及添加东西Date的意义.A Date是一个特定的时间点.将它们加在一起就像将丹佛和克利夫兰的纬度和经度加在一起,并期望坐标意味着有用的东西!

您的默认参数指定年份为2014,因此当您添加date1和date2时,您将获得date3.year = 2014 + 2014.我会提醒您避免使用默认参数,除非调用者几乎总是想要默认值.因为你指定day = 0,monthnum = 1,year = 2014,它会让你离开date3.