我只是在學習類,所以我嘗試了一些基本的東西。我有一個名爲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();
}
爲該函數添加一個重載有什麼問題:void outputMonthLetters(unsigned int monthNumber); – celavek
[提高可讀性](http://ideone.com/ve0PK) –
@Benjamin謝謝 – dukevin