作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我只是在学习类(class),所以我正在尝试一些基本的东西。我有一个名为 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();
}
最佳答案
你可能想要做的是这样的:
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,并且在您确定要查找的月份编号后调用采用月份编号的构造函数。
关于C++ 类 : Passing a parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590047/
我是一名优秀的程序员,十分优秀!