c++类:传递参数
C++ Class: Passing a parameter
我只是在学习课程,所以我在尝试一些基本的东西。我有一个名为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,并且在确定要查找的月号之后才调用接受月号的构造函数。
尝试在方法
上使用参数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) {
...
}
}
。向方法添加一个参数,并(可选地)将其设置为静态。但这并不是一个很好的以…
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用