开发者

C++ Class: Passing a parameter

I'm just learning classes so I'm trying something basic. I have a class called Month as shown below. For my first test, I want to supply a number from 1 through 12 and output the name of the month ie. 1 = Jan.

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:
 开发者_StackOverflow中文版     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;
    }
}

Here is where I have a question. I want to pass "num" into the outputMonthLetters function. How do I do this? The function is void, but there must be some way to get the variable into the class. Do I have to make the "month" variable public?

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


What you probably want to do is something like this:

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

Note that myMonth isn't declared until it's needed, and the constructor taking the month number is called after you determine what month number you are looking for.


Try using a parameter on the Method

void Month::outputMonthLetters(int num);

Than you could do:

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

I'm not the C++ guru, but don't you have to create an instance of Month?


Change your

void Month::outputMonthLetters() 

to

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

i.e. add a parameter to the method, and (optionally) make it static. But this is not a very good example of a class to start with...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜