Я пытаюсь создать простой класс даты, но я получаю ошибку на своем основном файле, который говорит, "вызов перегруженной Даты () неоднозначен". Я не уверен, почему, так как я думал, пока у меня были различные параметры для моего конструктора, я был в порядке. Вот мой код:
заголовочный файл:
#ifndef DATE_H
#define DATE_H
using std::string;
class Date
{
public:
static const int monthsPerYear = 12; // num of months in a yr
Date(int = 1, int = 1, int = 1900); // default constructor
Date(); // uses system time to create object
void print() const; // print date in month/day/year format
~Date(); // provided to confirm destruction order
string getMonth(int month) const; // gets month in text format
private:
int month; // 1 - 12
int day; // 1 - 31
int year; // any year
int checkDay(int) const;
};
#endif
Файл .cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include "Date.h"
using namespace std;
Date::Date()
{
time_t seconds = time(NULL);
struct tm* t = localtime(&seconds);
month = t->tm_mon;
day = t->tm_mday;
year = t->tm_year;
}
Date::Date(int mn, int dy, int yr)
{
if (mn > 0 && mn <= monthsPerYear)
month = mn;
else
{
month = 1; // invalid month set to 1
cout << "Invalid month (" << mn << ") set to 1.\n";
}
year = yr; // could validate yr
day = checkDay(dy); // validate the day
// output Date object to show when its constructor is called
cout << "Date object constructor for date ";
print();
cout << endl;
}
void Date::print() const
{
string str;
cout << month << '/' << day << '/' << year << '\n';
// new code for HW2
cout << setfill('0') << setw(3) << day; // prints in ddd
cout << " " << year << '\n'; // yyyy format
str = getMonth(month);
// prints in month (full word), day, year
cout << str << " " << day << ", " << year << '\n';
}
и мой main.cpp
#include <iostream>
#include "Date.h"
using std::cout;
int main()
{
Date date1(4, 30, 1980);
date1.print();
cout << '\n';
Date date2;
date2.print();
}
Date(int = 1, int = 1, int = 1900); // default constructor
Date(); // uses system time to create object
Оба они могут быть вызваны без параметров. Он не может быть сконструирован по умолчанию, потому что неясно, как построить объект.
Честно говоря, иметь эти три параметра с параметрами по умолчанию не имеет особого смысла. Когда я должен указать одно, а другие - нет?
Date(int = 1, int = 1, int = 1900); // default constructor
Date(); // uses system time to create object
Это делает ваш класс непростым. Читаемость серьезно нарушена, и вы даже получаете сообщение об ошибке, на которое не следует терять время. Пожалуйста, удалите ненужные параметры по умолчанию или второй конструктор.