Переопределение ошибки конструктора класса

#c

#c

Вопрос:

Я пытаюсь скомпилировать свой код и продолжаю получать ошибку:

переопределение ‘SimpleDate::SimpleDate(int, int, int)

Я думаю, что ошибка обычно возникает из-за того, что я не добавил #ifndef , #define , и #endif , но я их добавил.

simple_date.h:

 #ifndef SIMPLE_DATE_H
#define SIMPLE_DATE_H
#include <string>

class SimpleDate
{
  int _year, _month, _day;

public:
  // create a new 'SimpleDate' object with the given year, month, and day
  // throws an invalid_argument error if the date is invalid
  SimpleDate(int year, int month, int day) {};
  // returns the current year
  int year() const { return 0; };
  // returns the current month
  int month() const { return 0; };
  // returns the current day of the month
  int day() const { return 0; };
  // return string formatted as year-month-day with day an month 0 prefixed
  // i.e. 2000-01-01 is Jan 01, 2000
  std::string to_string() const { return ""; };
  // comparison operators
  bool operator==(const SimpleDateamp; lhs) const { return true; };
  bool operator!=(const SimpleDateamp; lhs) const { return true; };
  bool operator> (const SimpleDateamp; lhs) const { return true; };
  bool operator< (const SimpleDateamp; lhs) const { return true; };
  bool operator>=(const SimpleDateamp; lhs) const { return true; };
  bool operator<=(const SimpleDateamp; lhs) const { return true; };
  // returns 'true' if current year is a leap year
  bool is_leap() const { return true; };
  // returns the day of the week; 0 = Sunday
  // HINT: To calculate the day of the week, you need to have a known day. Use
  // 1970-01-01 which was a Thursday. Make sure to reference where you found
  // the algorithm or how you came up with it.
  int wday() const { return 0; };
  // returns the day of the year; Jan 1st = 1
  int yday() const { return 0; };
  // add one day to current date
  SimpleDateamp; incr_day() { SimpleDate dd {2016, 1, 1}; };
  SimpleDateamp; operator  () { SimpleDate dd {2016, 1, 1}; };
  // add n day(s) to current date
  SimpleDateamp; operator =(int n) { SimpleDate dd {2016, 1, 1}; };
  // subtract one day from current date
  SimpleDateamp; decr_day() { SimpleDate dd {2016, 1, 1}; };
  SimpleDateamp; operator--() { SimpleDate dd {2016, 1, 1}; };
  // subtract n day(s) from current date
  SimpleDateamp; operator-=(int n) { SimpleDate dd {2016, 1, 1}; };
  // add one month to current date
  SimpleDateamp; incr_month() { SimpleDate dd {2016, 1, 1}; };
  // subtract one month from current date
  SimpleDateamp; decr_month() { SimpleDate dd {2016, 1, 1}; };
  // add one year to current date
  SimpleDateamp; incr_year() { SimpleDate dd {2016, 1, 1}; };
  // subtract one year from current date
  SimpleDateamp; decr_year() { SimpleDate dd {2016, 1, 1}; };
  // returns 'true' if current date is a Monday
  bool is_monday() const { return true; };
  // returns 'true' if current date is a Tuesday
  bool is_tuesday() const { return true; };
  // returns 'true' if current date is a Wednesday
  bool is_wednesday() const { return true; };
  // returns 'true' if current date is a Thursday
  bool is_thursday() const { return true; };
  // returns 'true' if current date is a Friday
  bool is_friday() const { return true; };
  // returns 'true' if current date is a Saturday
  bool is_saturday() const { return true; };
  // returns 'true' if current date is a Sunday
  bool is_sunday() const { return true; };
    };

    #endif
  

simple_date.cpp:

 #include "simple_date.h"


SimpleDate::SimpleDate(int year, int month, int day)
{
    std::cout  >> year;
    if (year < 1970 || year > 2020)
    {
        throw invalid_argument("Don't care about years less than 1970 or greater than 2020");
    }
    else
    {
        _year = year;
    }
    if (month < 1 || month > 12)
    {
        throw invalid_argument("Not a real month");
    }
    else
    {
        _month = month;
    }
    if (day < 1 || day>31)
    {
        throw invalid_argument("Not a real day");
    }
    else if ((_month == 2 || _month == 4 || _month == 6 || _month == 9 || _month == 11) amp;amp; day > 30)
    {
        throw invalid_argument("Not a real day for this month");
    }
    else if (_month == 2 amp;amp; day == 29)
    {
        if (this.is_leap())
            _day = day;
        else
            hrow invalid_argument("Not a real day for this month and year");
    }
    else
        _day = day;
}
  

Комментарии:

1. Ну, у вас есть два определения, как указано в ошибке.

2. Просто удалите первое определение, {} . Проголосовали за закрытие как опечатку.

Ответ №1:

Вы определили конструктор в заголовочном файле, здесь:

 SimpleDate(int year, int month, int day) {};
  

Эти невинно выглядящие фигурные скобки превратили это объявление в определение. А затем компилятор очень расстроился, когда позже столкнулся с реальным определением этого конструктора. Просто удалите их:

 SimpleDate(int year, int month, int day);
  

Комментарии:

1. Это то, что я подумал. Учитель создал заголовок, поэтому я не хотел его менять. Я пытался удалить скобки раньше, но все равно получил ошибку. Я попробовал еще раз, и это работает. Спасибо миллион!