С ++ префикс оператора перегрузки приращения даты и ошибка постфикса - PullRequest
1 голос
/ 08 мая 2020

Я работаю над заданием, предлагающим пользователю ввести массив дат. Затем пользователю предлагается ввести 1 конкретную дату c. Эта дата будет увеличиваться как с использованием префикса, так и с помощью постфикса с использованием операторов перегрузки. Я реализовал свой код. Проблема заключается в том, что я получаю сообщение об ошибке «Неопределенный символ: Date :: leapYear (int)». Спасибо за помощь!

#include <iostream>

using namespace std;

class Date {
private:
    int mn;        //month component of a date
    int dy;        //day component of a date
    int yr;        //year comonent of a date

    //increment date
    void helpIncrement(); // incrementing date
    static const int days[]; // array of days per month

public:
    //constructors
    Date() : mn(0), dy(0), yr(0)
    {}
    Date(int m, int d, int y) : mn(m), dy(d), yr(y)
    {}

    //access functions
    int getDay() const
    {
        return dy;
    }
    int getMonth() const
    {
        return mn;
    }
    int getYear() const
    {
        return yr;
    }
    bool operator==(Date const &d) const;   //overload equal to
    bool operator>(Date const &d) const;    //overload greater than
    bool operator<(Date const &d) const;    //overload less than

    //modifier functions
    void setDay(int d)
    {
        dy = d;
    }
    void setMonth(int m)
    {
        mn = m;
    }
    void setYear(int y)
    {
        yr = y;
    }
    void setDate(int m, int d, int y)
    {
        mn = m; dy = d; yr = y;
    }

    //input/output functions
    friend istream& operator>>(istream& read, Date& d);   //overload friend read
    friend ostream& operator<<(ostream& write, Date& d);   //overload friend write
    void GetDates();
    void Sort();

    //increment date
    Date &operator++(); // prefix increment operator
    Date operator++( int ); // postfix increment operator
    bool endOfMonth( int ) const; // is date at the end of month
    static bool leapYear( int ); // is date in a leap year

};

//Date class member functions
bool Date::operator==(Date const &d) const      //overload equal to
{
    return (mn == d.mn) && (dy == d.dy) && (yr == d.yr);
}

bool Date::operator>(Date const &d) const       //overload greater than
{
    if ((yr > d.yr) ||
        ((yr == d.yr) && (mn > d.mn)) ||
        ((yr == d.yr) && (mn == d.mn) && (dy > d.dy)))
        return true;

    return false;
}

bool Date::operator<(Date const &d) const       //overload less than
{
    if ((yr < d.yr) ||
        ((yr == d.yr) && (mn < d.mn)) ||
        ((yr == d.yr) && (mn == d.mn) && (dy < d.dy)))
        return true;

    return false;
}

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

//increment the date
const int Date::days[] =
   { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

void Date::helpIncrement()
{
   // day is not end of month
   if ( !endOfMonth( dy ) )
       ++dy; // increment day
   else
       if ( mn < 12 ) // day is end of month and month < 12
       {
           ++mn; // increment month
           dy = 1; // first day of new month
       }
       else // last day of year
       {
           ++yr; // increment year
           mn = 1; // first month of new year
           dy = 1; // first day of new month
       } // end else
}

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

Date Date::operator++( int )
{
   Date temp = *this;
   helpIncrement();
    return temp;
}

istream& operator >>(istream& read, Date& d) //friend read in
{
    char skip_char;

    read >> d.mn >> skip_char >> d.dy >> skip_char >> d.yr;
    return read;
}

ostream& operator <<(ostream& write, Date& d) //friend write
{
    if (d.mn < 10)
        cout << '0';
    cout << d.mn << '/';
    if (d.dy < 10)
        cout << '0';
    cout << d.dy << '/';
    if (d.yr < 1000)
        cout << '0';
    if (d.yr < 100)
        cout << '0';
    if (d.yr < 10)
        cout << '0';
    cout << d.yr;
    return write;
}

void GetDates(Date l[], int &n)      //reads list l, and returns count in n
   {

       cout << "How many date values are to be processed (1 - 100)? ";
       cin >> n;

       while ((n < 0) || (n > 100)) {
           cout << "Invalid value; enter number between 0 and 100: ";
           cin >> n;
       }

       for (int i = 0; i < n; i++) {
           cout << "Enter a date (mm/dd/yyyy): ";
           cin >> l[i];
       }
   }

void Sort(Date l[], int n, char order)
{

    if (order == 'A'||order == 'a'){              //ascending order

        for (int i = 0; i < n; i++){
            for (int j = i + 1; j < n; j++){
                if(l[i].operator>(l[j])){
                   Date temp = l[i];
                   l[i] = l[j];
                   l[j] = temp;
               }
            }
        }

    } else if (order == 'D'||order == 'd'){       //descending order
        for (int i = 0; i < n; i++){
            for (int j = i + 1; j < n; j++){
                if(l[i].operator<(l[j])){
                   Date temp = l[i];
                   l[i] = l[j];
                   l[j] = temp;
               }
            }
        }

    }else{
        cout << "invalid ordering" << endl;
    }
}

1 Ответ

4 голосов
/ 08 мая 2020

Вы объявили функцию static bool leapYear( int );, но не предоставили определение (по крайней мере, не в коде, который вы показываете).

Добавьте определение, подобное этому (вне определения класса):

bool Date::leapYear( int year )
{
    bool answer = // PLEASE check the validity of the algorithm!
        ( (year % 4 == 0) && (year % 100 != 0) ) || (year % 400 == 0);
    // Maybe add an .. && (year >= 1752) ??
    return answer;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...