簡體   English   中英

C ++類:傳遞參數

[英]C++ Class: Passing a parameter

我只是在學習課程,所以我在嘗試一些基本的東西。 我有一個名為“月”的課程,如下所示。 對於我的第一個測試,我想提供一個從1到12的數字並輸出月份的名稱,即。 1 =一月

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函數。 我該怎么做呢? 該函數是無效的,但是必須有某種方法可以將變量添加到類中。 我必須公開“ month”變量嗎?

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

您可能想做的是這樣的:

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,並在確定要查找的月份號之后調用采用月份號的構造函數。

嘗試在方法上使用參數

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 ++專家,但是您是否不必創建Month的實例?

改變你的

void Month::outputMonthLetters() 

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

即向該方法添加參數,並(可選)使其為靜態。 但這不是一個很好的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM