2011-09-28 73 views
1

我只是在學習類,所以我嘗試了一些基本的東西。我有一個名爲Month的課程,如下所示。對於我的第一個測試,我想提供一個從1到12的數字並輸出月份的名字,即。 1 = 1月C++類:傳遞參數

class Month 
{ 
public: 
    Month (char firstLetter, char secondLetter, char thirdLetter); // constructor 
    Month (int monthNum); 
    Month(); 
    void outputMonthNumber(); 
    void outputMonthLetters(); 
    //~Month(); // destructor 
private: 
    int month; 
}; 
Month::Month() 
{ 
    //month = 1; //initialize to jan 
} 
void Month::outputMonthNumber() 
{ 
    if (month >= 1 && month <= 12) 
    cout << "Month: " << month << endl; 
    else 
    cout << "Not a real month!" << endl; 
} 

void Month::outputMonthLetters() 
{ 
    switch (month) 
    { 
    case 1: 
     cout << "Jan" << endl; 
     break; 
    case 2: 
     cout << "Feb" << endl; 
     break; 
    case 3: 
     cout << "Mar" << endl; 
     break; 
    case 4: 
     cout << "Apr" << endl; 
     break; 
    case 5: 
     cout << "May" << endl; 
     break; 
    case 6: 
     cout << "Jun" << endl; 
     break; 
    case 7: 
     cout << "Jul" << endl; 
     break; 
    case 8: 
     cout << "Aug" << endl; 
     break; 
    case 9: 
     cout << "Sep" << endl; 
     break; 
    case 10: 
     cout << "Oct" << endl; 
     break; 
    case 11: 
     cout << "Nov" << endl; 
     break; 
    case 12: 
     cout << "Dec" << endl; 
     break; 
    default: 
     cout << "The number is not a month!" << endl; 
    } 
} 

這裏是我有一個問題。我想將「num」傳遞給outputMonthLetters函數。我該怎麼做呢?該函數是無效的,但是必須有一些方法來將變量放入類中。我是否必須公開「月」變量?

int main(void) 
{ 
    Month myMonth; 
    int num; 
    cout << "give me a number between 1 and 12 and I'll tell you the month name: "; 
    cin >> num; 
    myMonth.outputMonthLetters(); 
} 
+0

爲該函數添加一個重載有什麼問題:void outputMonthLetters(unsigned int monthNumber); – celavek

+1

[提高可讀性](http://ideone.com/ve0PK) –

+0

@Benjamin謝謝 – dukevin

回答

4

你可能想要做的是這樣的:

int num; 
cout << "give me a number between 1 and 12 and I'll tell you the month name: "; 
cin >> num; 
Month myMonth(num); 
myMonth.outputMonthLetters(); 

注意myMonth沒有聲明,直到它的需要,並構造採取月份數字是叫你確定哪些一個月後你正在尋找的號碼。

+0

我假設你實際上實現了'Month :: Month(int)'構造函數;如果你沒有,代碼是'Month :: Month(int m):month(m){}' –

+0

好極了!謝謝,我明白你現在是怎麼做到的! – dukevin

1

嘗試使用參數的方法

void Month::outputMonthLetters(int num); 

比你可以這樣做:

Month myMonth; 
int num; 
cout << "give me a number between 1 and 12 and I'll tell you the month name: "; 
cin >> num; 
myMonth.outputMonthLetters(num); 

我不是C++大師,但你不必須創建月的一個實例?

0

更改

void Month::outputMonthLetters() 

static void Month::outputMonthLetters(int num) 
{ 
    switch(num) { 
    ... 
    } 
} 

即一個參數添加到方法,和(可選),使其靜態的。但是這不是一個很好的例子,開始...

+0

你爲什麼要改變它?它被稱爲重載 - 可以有多個具有相同名稱但具有不同參數類型或參數數量的方法。 – celavek