【问题标题】:C++ Class: Passing a parameterC++ 类:传递参数
【发布时间】:2011-09-28 21:49:25
【问题描述】:

我只是在学习课程,所以我正在尝试一些基本的东西。我有一个名为 Month 的课程,如下所示。对于我的第一个测试,我想提供一个从 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 函数。我该怎么做呢?该函数是无效的,但必须有某种方法可以将变量放入类中。我必须公开“月份”变量吗?

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);
  • 任何时候你发现唯一改变的是一个数字,你可能想要一个数组。

标签: c++ class


【解决方案1】:

你可能想做的是这样的:

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 直到需要时才会声明,并且在您确定要查找的月份编号后调用获取月份编号的构造函数。

【讨论】:

  • 我假设您实际上已经实现了Month::Month(int) 构造函数;如果你没有,代码是Month::Month(int m) : month(m) {}
  • 太棒了!谢谢,我知道你现在是怎么做到的了!
【解决方案2】:

尝试在方法上使用参数

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 的实例吗?

【讨论】:

    【解决方案3】:

    改变你的

    void Month::outputMonthLetters() 
    

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

    即向该方法添加一个参数,并(可选)使其成为静态的。但这不是一个很好的类开始的例子......

    【讨论】:

    • 你为什么要改变它?这称为重载 - 您可以拥有多个名称相同但参数类型或参数数量不同的方法。
    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2021-09-07
    相关资源
    最近更新 更多