2010-04-20 63 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; 
}