2010-04-20 75 views
4

我正在尝试创建一个简单的日期类,但是在我的主文件中出现错误,说“重载的Date()调用不明确。”我不知道为什么,因为我认为只要我的构造函数有不同的参数,我就没问题。这里是我的代码:模糊的构造函数调用

头文件:

#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(); 


} 
+0

我同意GMAN写道。但是,如果你声明默认构造函数是私有的,编译器会抱怨同样的错误。实际上,它试图组装两个“相同”或相同的方法。 – 2010-04-20 08:59:05

+0

您还应该在参数中包含参数名称。虽然他们没有技术上的必要性,但如果没有挖掘源文件,就无法知道用户是应该提供(月,日,年)还是(日,月,年)。我还会根据GMan关于不提供默认参数的建议。在什么情况下,只要在六月份,有人会随机抽出一天呢? – 2010-04-20 09:16:55

回答

20
Date(int = 1, int = 1, int = 1900); // default constructor 
Date(); // uses system time to create object 

这些都是调用无参数。它不能被默认构造,因为如何构造对象是模糊的。老实说,有三个默认参数没有多大意义。我什么时候会指定一个而不是其他的?

0
Date(int = 1, int = 1, int = 1900); // default constructor 
Date(); // uses system time to create object 

让你的课变得不再简单。可读性严重受损,甚至出现错误,您不应该浪费时间。请删除无用的默认参数或第二个构造函数。

+3

我认为如果简单是目标,他应该删除使用系统时间的表单。设置默认日期比根据使用时间更改更有意义。我更喜欢9Feb64作为我的默认日期,但细节并不重要。 – 2010-04-20 09:40:20

1

你应该申报的两个构造函数:

Date(int day, int month, int year) 
{ 
    this->day = day; 
    this->month = month; 
    this->year = year; 
} 
Date(); // uses system time to create object 
{ 
    this->day = 1; 
    this->month = 1; 
    this->year = 1900; 
}