使用类在c ++中添加年实现 [英] Adding the year implementation in c++ using a class

查看:176
本文介绍了使用类在c ++中添加年实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个程序在一个类中,并添加到每个日期一个。
所以如果日期是:1/1/2014我想要的是2/2/2015。

I am trying to make a program inside a class and add to the date one in each. So if the date was: 1/1/2014 I want it to be 2/2/2015.

我能够找出部分日期和月份,但是,由于某种原因,我得到一个奇怪的数字为一年。

I was able to figure out the part for the day and the month, however, for some reason I am getting a strange number for the year.

当我试图调试程序,我发现它正在打印

when I tried to debug the program I found out that it's printing the following

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

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

Here is what I've done so far:

      #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;
}


推荐答案

code> Date 表示,以及在 Date s中添加内容的意思。 日期是特定时间点。将它们添加在一起将像添加丹佛和克利夫兰的纬度和经度,并期望坐标意味着有用的!

Think carefully about what a Date represents, and what adding things to Dates would mean. A Date is a particular point in time. Adding them together would be like adding the latitude and longitude of Denver and Cleveland together and expecting the coordinate to mean something useful!

您的默认参数指定年份为2014年,所以当你添加date1和date2时,你得到date3.year = 2014 + 2014.我会提醒你避免默认参数,除非在调用者几乎总是需要默认值。因为你指定了day = 0,monthnum = 1,year = 2014,所以它也会让你脱离date3。

Your default parameters specify the year to be 2014, so when you add date1 and date2 you get date3.year = 2014 + 2014. I would caution you to avoid default parameters except in cases where the caller will almost always want the default. It's throwing you off for date3 as well, because you're specifying that day=0, monthnum=1, year=2014.

这篇关于使用类在c ++中添加年实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆