gpt4 book ai didi

C++将变量传递给类到函数

转载 作者:行者123 更新时间:2023-11-28 03:46:11 24 4
gpt4 key购买 nike

我有一个类“Month”,它具有无效的成员函数和无效的参数传递。我需要重载构造函数(我认为),但编译器不喜欢我的尝试。

class Month
{
public:
Month(char firstLetter, char secondLetter, char thirdLetter); //?
Month::Month(int m) : month(m) {} //Want above ^ to look like this
Month();
void outputMonthNumber();
void outputMonthLetters();
//~Month(); // destructor
private:
int month;
};
void Month::outputMonthNumber()
{
if (month >= 1 && month <= 12)
cout << "Month: " << month << endl;
else
cout << "Not a real month!" << endl;
}
void Month::outputMonthLetters()
{
const char * monthNames[] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};

const char * output = "The number is not a month!";
if (month >= 1 && month <= 12)
output = monthNames[month - 1];

cout << output;
}

就像输出月份数字的方式一样,我正在尝试为 outputMonthNumber 做同样的事情,但我无法理解它。

int main(void)
{
int num;
char firstLetter, secondLetter, thirdLetter;
cout << "give me a number between 1 and 12 and I'll tell you the month name: ";
cin >> num;
Month myMonth(num);
myMonth.outputMonthLetters();
cout << endl << "Give me a 3 letter month and I'll give you the month #: ";
cin >> firstLetter >> secondLetter >> thirdLetter;
/*===How would I pass the parameters to the class?===*/
//Month herMonth(firstLetter, secondLetter, thirdLetter);
//herMonth.outputMonthNumber();
}

类的所有成员函数都传递void参数。我知道如何通过一个,但我似乎无法让它正确重载。

最佳答案

这样做:

class Month
{
public:
Month(char firstLetter, char secondLetter, char thirdLetter) :
first(firstLetter),second(secondLetter),third(thirdLetter)
{
const char * monthNames[] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
for ( int i = 0 ; i < 12 ; i++ )
if ( monthNames[i][0] == first && monthNames[i][1] == second && monthNames[i][2] == third )
month = i + 1;
}
Month::Month(int m) : month(m) {} //Want above ^ to look like this
Month();
void outputMonthNumber();
void outputMonthLetters();
//~Month(); // destructor
private:
int month;
char first;
char second;
char third;
};

关于C++将变量传递给类到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7602298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com