【问题标题】:C++ Store How many days ago a date was in a Date objectC++ 存储日期对象中的日期是多少天前
【发布时间】:2017-03-27 23:27:57
【问题描述】:

我正在尝试将一天前多少天存储到 C++ 中的对象中。这本书说它这样做是因为 C++ 没有一个正确的日期定义,或者至少没有一个不跟踪 1970 年之后的日子的定义。我一直在尝试在闲暇时阅读一本书。该脚本以获取三个输入开始,即月、日和年。它使它们通过一个构造函数,该构造函数添加了第四个参数 old,默认为 0。

在那之后,我的主程序尝试运行一个函数来计算那天之前多少天使用了过去几天函数,这是个人编写的 Date 类的一部分,并尝试将其分配给对象中 old 的第四个参数。

这里有 main.cpp/驱动程序。构造函数工作并创建日期类型的对象。

#include <iostream>
#include "Date.h" // Date class definition
#include <time.h>
#include <ctime>
using namespace std;

int main() {
    int birthMonth = 0;
    int birthDay = 0;
    int birthYear = 0;

    int dateToMonth = 0;
    int dateToDay = 0;
    int dateToYear = 0;

    cout << "Enter birth month (1-12): ";
    cin >> birthMonth;
    cout << "Enter birth day (1-31): ";
    cin >> birthDay;
    cout << "Enter birth year (1900 - 2000): ";
    cin >> birthYear;

    Date birthDate (birthMonth, birthDay, birthYear);

    cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
    cin >> dateToMonth;
    cout << "Enter Day to calculate it to (1-31): ";
    cin >> dateToDay;
    cout << "Enter Year to calculate it to: ";
    cin >> dateToYear;

    Date dateTo (dateToMonth, dateToDay, dateToYear);

    Date d1( 12, 27, 2010, 0 ); // December 27, 2010
    Date d2; // defaults to January 1, 1900

    Date::pastDays(birthDate);
    Date::pastDays(dateTo);

    // birthDate = birthDate - dateTo;
    cout << birthDate.old;
}

当我尝试使用它时,...
日期::过去的日子(出生日期); 我收到错误消息“无法在没有对象的情况下调用成员函数 'int Date::pastDays(Date)'。”

我似乎正在通过那里传递对象。

这是 Date.h 标头。

#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>

class Date
  {
    friend std::ostream &operator<<( std::ostream &, const Date & );
public:
    Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
    void setDate( int, int, int, int ); // set month, day, year
    Date &operator++(); // prefix increment operator
    Date operator++( int ); // postfix increment operator
    Date &operator+=( unsigned int ); // add days, modify object
    int pastDays (Date);
    static bool leapYear( int ); // is date in a leap year?
    bool endOfMonth( int ) const; // is date at the end of month?
    unsigned int month;
    unsigned int day;
    unsigned int year;
    int old;
    static const std::array< unsigned int, 13 > days; // days per month
    void helpIncrement(); // utility function for incrementing date
}; // end class Date

#endif

这里有主要的 Date.cpp 程序。它首先创建用于复制输入的日、月和年的变量。我尝试设计它,以便 pastDays 获取该信息,将日期和月份递减到 1 月 1 日,并将其存储在 daysAgo 的变量中,即创建的负数天数。

然后它增加年份,并根据是否是闰年增加 365 或 366。然后它将当前日期和月份递增回当前日期,并将更改添加回 daysAgo 变量。然后它尝试将其作为 entryDay 信息,但在旧参数中,以便原始对象现在已填写该信息。至少这是计划。

#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
using namespace std;

   // initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Date constructor
Date::Date( int month, int day, int year, int old )
  {
    setDate( month, day, year, old );
  } // end Date constructor

// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
  {
    if ( mm >= 1 && mm <= 12 )
        month = mm;
    else
        throw invalid_argument( "Month must be 1-12" );

    if ( yy >= 1900 && yy <= 2100 )
        year = yy;

    // test for a leap year
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
            if (dd >= 1 || dd <= 31)
            day == dd;
        }
        if (month == 4 || month == 6 || month == 9 || month == 11){
            if (dd >= 1 || dd <= 30)
            day == dd;
        }
        if (month == 2)
            if ( year % 4 != 0 ) {
    if (dd >= 1 || dd <= 29)
    day == dd;
            }
        if (month == 2)
            if ( year % 4 != 0 ) {
    if (dd >= 1 || dd <= 28)
    day == dd;
            }
        else {
            throw invalid_argument(
    "Day is out of range for current month and year" );
        }
} // end function setDate

// overloaded prefix increment operator
Date &Date::operator++()
{
    helpIncrement(); // increment date
    return *this; // reference return to create an lvalue
} // end function operator++

// overloaded postfix increment operator; note that the
// dummy integer parameter does not have a parameter name
Date Date::operator++( int )
{
    Date temp = *this; // hold current state of object
    helpIncrement();

// return unincremented, saved, temporary object
    return temp; // value return; not a reference return
} // end function operator++

// add specified number of days to date
Date &Date::operator+=( unsigned int additionalDays )
{
    for ( int i = 0; i < additionalDays; ++i )
        helpIncrement();
    return *this; // enables cascading
} // end function operator+=


Date pastDays (Date &entryDay) {
    //Creating Today date object
    time_t t = time(0);
    struct tm * now = localtime(&t);
    int currentYear = now -> tm_year + 1900;
    int currentMonth = now -> tm_mon + 1;
    int currentDay = now -> tm_mday;

    int birthMonth = entryDay.month;
    int birthDay = entryDay.day;
    int birthYear = entryDay.year;

    //The variable that will be assigned to the old parameter, which can then be subtracted from another time.
    int daysAgo = 0;

    //Lowering days to 1, to make transition between years easier.
    while (birthDay > 1){
        birthDay--;
        daysAgo--;
    }

    cout << daysAgo;

    //Lowering months to 1, to make transition between years easier.
    while (birthMonth > 1){
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth--;
            daysAgo -= 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth--;
            daysAgo -= 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth--;
    daysAgo -= 29;
            }
        else {
            birthMonth--;
            daysAgo -= 28;
        }
    }


    cout << daysAgo;
    //Incrementing year to current year
    while (birthYear < currentYear){
        if ( currentYear % 400 == 0 ||
        ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
            daysAgo = daysAgo + 366;
            birthYear++;
        }
        else {
            daysAgo = daysAgo + 365;
            birthYear++;
        }
    }


    cout << daysAgo;
    // Incrementing to current month
    while (birthMonth < currentMonth) {
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth++;
            daysAgo += 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth++;
            daysAgo += 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth++;
    daysAgo += 29;
            }
        else {
            birthMonth++;
            daysAgo += 28;
        }
    }

    cout << daysAgo;
    //Incrementing to current day, and adding the days to the daysAgo
    while (birthDay < currentDay){
        birthDay++;
        daysAgo++;
    }



    cout << daysAgo;
    //Assigning DaysAgo to input parameter.old
    entryDay.old = daysAgo;
    return(entryDay);
}


// if the year is a leap year, return true; otherwise, return false
bool Date::leapYear( int testYear )
{
    if ( testYear % 400 == 0 ||
      ( testYear % 100 != 0 && testYear % 4 == 0 ) )
        return true; // a leap year
    else
        return false; // not a leap year
} // end function leapYear

// determine whether the day is the last day of the month
bool Date::endOfMonth( int testDay ) const
{
    if ( month == 2 && leapYear( year ) )
        return testDay == 29; // last day of Feb. in leap year
    else
        return testDay == days[ month ];
} // end function endOfMonth

// function to help increment the date
void Date::helpIncrement()
{
    // day is not end of month
    if ( !endOfMonth( day ) )
        ++day; // increment day
    else
        if ( month < 12 ) // day is end of month and month < 12
        {
            ++month; // increment month
            day = 1; // first day of new month
        } // end if
        else // last day of year
        {
            ++year; // increment year
            month = 1; // first month of new year
            day = 1; // first day of new month
        } // end else
} // end function helpIncrement

// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
  static string monthName[ 13 ] = { "", "January", "February",
        "March", "April", "May", "June", "July", "August",
        "September", "October", "November", "December" };
  output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
  return output; // enables cascading
} // end function operator<<

我的主要问题是我无法计算几天前的数据,并将其存储在第四个 Date 参数中。

点 点 点 点 点

又过了几个小时,我现在修改了程序来计算它已经过去了多少天。我在这里列出它供其他人查看。也许它会帮助其他人。

main.cpp

#include <iostream>
#include <time.h>
#include <ctime>
#include "Date.cpp" // Date class definition
using namespace std;

int main() {
    unsigned int birthMonth = 0;
    unsigned int birthDay = 0;
    unsigned int birthYear = 0;

    unsigned int dateToMonth = 0;
    unsigned int dateToDay = 0;
    unsigned int dateToYear = 0;

    cout << "Enter birth month (1-12): ";
    cin >> birthMonth;
    cout << "Enter birth day (1-31): ";
    cin >> birthDay;
    cout << "Enter birth year (1900 - 2000): ";
    cin >> birthYear;

    Date birthDate (birthMonth, birthDay, birthYear);

    cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
    cin >> dateToMonth;
    cout << "Enter Day to calculate it to (1-31): ";
    cin >> dateToDay;
    cout << "Enter Year to calculate it to: ";
    cin >> dateToYear;

    Date dateTo (dateToMonth, dateToDay, dateToYear);

    pastDays(birthDate);
    pastDays(dateTo);

    cout << "\nHow many days ago is the birth date? " << birthDate.old << endl;
    cout << "How many days ago is the secondary date? " << dateTo.old << endl;

}

这里是 date.h

#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>

class Date
  {
    friend std::ostream &operator<<( std::ostream &, const Date & );
public:
    Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
    void setDate( int, int, int, int ); // set month, day, year
//    friend Date operator - (Date &ob1, Date &ob2);
    Date &operator-(); // Modified Line for Assignment
    Date &operator-(Date); // Modified Line for Assignment
    void pastDays (Date);
    static bool leapYear( int ); // is date in a leap year?
    unsigned int month;
    unsigned int day;
    unsigned int year;
    int old;
    static const std::array< unsigned int, 13 > days; // days per month
}; // end class Date

#endif

这里是 Date.cpp

#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
#include "Date.h" // Date class definition
using namespace std;

   // initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Date constructor
Date::Date( int month, int day, int year, int old )
  {
    setDate( month, day, year, old );
  } // end Date constructor

// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
  {
    if ( mm >= 1 && mm <= 12 )
        month = mm;
    else
        throw invalid_argument( "Month must be 1-12" );

    if ( yy >= 1900 && yy <= 2100 )
        year = yy;

    // test for a leap year
//        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
//            if (dd >= 1 || dd <= 31)
//            day == dd;
//        }
//        if (month == 4 || month == 6 || month == 9 || month == 11){
//            if (dd >= 1 || dd <= 30)
//            day == dd;
//        }
//        if (month == 2)
//            if ( year % 4 != 0 ) {
//                if (dd >= 1 || dd <= 29)
//                day == dd;
//            }
//        if (month == 2)
//            if ( year % 4 != 0 ) {
//                if (dd >= 1 || dd <= 28)
//                day == dd;
//            }
//        else {
//            throw invalid_argument(
//                "Day is out of range for current month and year" );
//        }

    if ( ( month == 2 && leapYear( year ) && dd >= 1 && dd <= 29 ) ||
        ( dd >= 1 && dd <= days[ month ] ) )
        day = dd;
    else
        throw invalid_argument(
            "Day is out of range for current month and year" );


} // end function setDate

void pastDays (Date &entryDay) {
    //Creating Today date object
    time_t t = time(0);
    struct tm * now = localtime(&t);
    int currentYear = now -> tm_year + 1900;
    int currentMonth = now -> tm_mon + 1;
    int currentDay = now -> tm_mday;

    int birthMonth = entryDay.month;
    int birthDay = entryDay.day;
    int birthYear = entryDay.year;

    //The variable that will be assigned to the old parameter, which can then be subtracted from another time.
    int daysAgo = 0;
    entryDay.old = 0;

    cout << endl;
    cout << "First" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering days to 1, to make transition between years easier.
//    while (birthDay > 1){
//        birthDay--;
//        daysAgo--;
//    }

    daysAgo = daysAgo - birthDay;
    daysAgo++;
    birthDay = 1;

    cout << endl;
    cout << "Second" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering months to 1, to make transition between years easier.
    while (birthMonth > 1){
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth--;
            daysAgo -= 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth--;
            daysAgo -= 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth--;
    daysAgo -= 29;
            }
        else {
            birthMonth--;
            daysAgo -= 28;
        }
    }

    cout << endl;
    cout << "Third" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing year to current year
    while (birthYear < currentYear){
        if ( currentYear % 400 == 0 ||
        ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
            daysAgo = daysAgo + 366;
            birthYear++;
        }
        else {
            daysAgo = daysAgo + 365;
            birthYear++;
        }
    }

    cout << endl;
    cout << "Fourth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    // Incrementing to current month
    while (birthMonth < currentMonth) {
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth++;
            daysAgo += 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth++;
            daysAgo += 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth++;
    daysAgo += 29;
            }
        else {
            birthMonth++;
            daysAgo += 28;
        }
    }

    cout << endl;
    cout << "Fifth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing to current day, and adding the days to the daysAgo
    while (birthDay < currentDay){
        birthDay++;
        daysAgo++;
    }


    cout << endl;
    cout << "Sixth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Assigning DaysAgo to input parameter.old
    entryDay.old = daysAgo;
}


Date operator - (Date &date1, Date &date2)
    {

    Date temp;
    temp.old   = date1.old   - date2.old;
    if(temp.old < 0)
    {
        temp.old = temp.old * -1;
    }
    return(temp);
    }

//Date operator-(Date birthDate)
////friend Distance operator - (Date &birthDate, Date &today)
//    {
////    int birthMonth = birthDate.month;
////    int birthDay = birthDate.day;
////    int birthYear = birthDate.year;
////    int birthOld = 0;
////    Date temp (birthDate.month, birthDate.day, birthDate.year, birthDate.old);
//
////    pastDays(today);
////    pastDays(birthDate);
//
////    int currentMonth = today.month;
////    int currentDay = today.day;
////    int currentYear = today.year;
//
////    int date1 = pastDays(today);
////    int date2 = pastDays(birthDate);
//    Date temp (birthDate.month, birthDate.day, birthDate.year);
//
////    int month, int day, int year, int old
////    temp.month = this -> month;
////    temp.month = this -> day;
////    temp.month = this -> year;
////    Date temp = *this;
//    cout << temp.old;
//
//    temp.old = *this -> old - birthDate.old;
//        //Here I get "Error: Invalid use of 'this' in non-member function;
//
//    return(temp);
//}

bool Date::leapYear( int testYear )
{
    if ( testYear % 400 == 0 ||
      ( testYear % 100 != 0 && testYear % 4 == 0 ) )
        return true; // a leap year
    else
        return false; // not a leap year
} // end function leapYear

// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
  static string monthName[ 13 ] = { "", "January", "February",
        "March", "April", "May", "June", "July", "August",
        "September", "October", "November", "December" };
  output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
  return output; // enables cascading
} // end function operator<<

【问题讨论】:

    标签: c++ date object


    【解决方案1】:

    pastDays() 的结构令人困惑和奇怪。

    Date::pastDays(birthDate);   --->   birthDate.pastDate(birthDate) // Would compile and maybe work.
                               Change to
    Date::pastDays(dateTo);      --->   dateTo.pastDate(dateTo)       // Would compile and maybe work.
    

    但是,如果您只是将该函数的签名更改为:

    void pastDays (Date &entryDay);
    

    并且删除最后的 return entryDay 语句,因为值已经通过引用传递,所以 entryDay 将在函数执行后。

    现在,在调用函数的代码段中,不再使用范围运算符 (::):

    Date::pastDays(birthDate);   --->   pastDate(birthDate);compile and maybe work.
                               Change to
    Date::pastDays(dateTo);      --->   pastDate(dateTo);
    

    【讨论】:

    • @Greg 有帮助吗?
    • 谢谢。我已经把过去的日子变成了虚无。这是有道理的,因为我没有将它声明为 const,所以我将直接更改内存值,所以现在它不需要返回类型,因为它是一个 void。出色的通话。回到 main.cpp,我尝试更改... pastDate(dateTo);过去日期(出生日期);现在它让我在这个范围内没有声明“pastDate”。我认为它必须用 Date:: 标记,以便程序知道在哪里可以找到它。对不起,我只是新人。
    • 没有问题 :) 如果有帮助,您可以标记为正确答案吗?
    • 嘿,我想我已经很接近了,我想一旦我完成了你就会收到支票。 ^.^ 我确实将 Date.h 标头更改为不再使用 int ,而是使用 void ,但我仍然有一点点泡菜。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2015-08-24
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多