【问题标题】:Adding the year implementation in c++ using a class使用类在 C++ 中添加年份实现
【发布时间】: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”类型的情况。尤其是你们中的一些人可以追溯到足够远的历史,并在实际的日历中遇到根本性的变化

标签: c++ class


【解决方案1】:

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

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

【讨论】:

  • 非常感谢。因此,我认为要使其正常工作,我应该只添加 + 而不是添加年份。
【解决方案2】:
return Date(day+date.day,monthnum+ date.monthnum ,date.year+year);

在这里,您将 date1 的每年、月份和日期添加到 date2。所以 2014 + 2014 = 4028! 如果你想为每个部分添加“1”,请编写一个函数来返回 monthnum + 1、day + 1 和 year + 1。

【讨论】:

  • 非常感谢。因此,我认为要使其正常工作,我应该只添加 + 而不是添加年份。
猜你喜欢
  • 2023-01-16
  • 2021-02-06
  • 2019-06-21
  • 2015-12-24
  • 2013-03-05
  • 2012-04-02
  • 2022-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多