运算符重载C++
问题描述:
我正在试图创建一个程序,要求用户输入一个月的输入。然后程序会显示月份,接下来的月份,前一个月份,之后的第五个月份以及之前的第七个月份。我无法让程序减去一个月,或其他下面的操作。我只能得到它来添加下个月。有什么想法吗?运算符重载C++
#include <iostream>
#include <string>
using namespace std;
enum Month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
Month& operator++(Month& theMonth)
{
if (theMonth == DEC)
theMonth = JAN;
else
theMonth = static_cast<Month>(theMonth + 1);
return theMonth;
}
Month& operator--(Month& theMonth)
{
if (theMonth == JAN)
theMonth = DEC;
else
theMonth = static_cast<Month>(theMonth - 1);
return theMonth;
}
ostream &operator<<(ostream &output, Month &theMonth)
{
switch (theMonth){
case JAN: output << "January";
break;
case FEB: output << "February";
break;
case MAR: output << "March";
break;
case APR: output << "April";
break;
case MAY: output << "May";
break;
case JUN: output << "June";
break;
case JUL: output << "July";
break;
case AUG: output << "Augest";
break;
case SEP: output << "September";
break;
case OCT: output << "October";
break;
case NOV: output << "November";
break;
case DEC: output << "December";
break;
}
return output;
}
istream &operator>>(istream &input, Month &theMonth)
{
int value;
input >> value;
theMonth = static_cast<Month>(value);
return input;
}
#include<iostream>
#include<string>
#include "Month.h"
using namespace std;
int main()
{
Month myMonth;
cout << "Enter Month (1-12): ";
cin >> myMonth;
cout << "You selected month, " << myMonth << " \n" << endl;
cout << "The next month after the month you entered is " << myMonth++ << "\n" << endl;
cout << "The month before the month you entered is " << myMonth-- << "\n" << endl;
cout << "Five months after the month you entered is " << myMonth+= << "\n" << endl;
cout << "Seven months before the month you entered is " << myMonth-= << "\n" << endl;
cin.ignore();
cin.get();
return 0;
}
答
而不是使用一个枚举值的,我会建议不同的类,它包装一个int:
class Month {
int month_num; // Month, 0-11. (0-January, 1-February, etc...)
public:
// ...
};
然后,所有月份的操作,例如加,减,加n
个月,减n
个月等 - 它们都变成微不足道的模12算术。
显示月份的名称也变得简单,因为它可能可以:
static const char * const months[] = {
"January",
"February",
// etc... I'm too lazy to type
"December"
};
因此,实现您std::ostream
operator<<
过载时,你猜怎么着“月[month_num]”会为你做什么?
运营++变成:
month_num=(month_num+1) % 12;
operator--成为
month_num=(month_num+11) % 12; // Yes, I just can't wrap negative values and modulo inside my brain, this is easier to grok...
运营商+ =,以n
添加到月份数,成为
month_num=(month_num+n) % 12;
等等
+0
感谢所有的帮助!我不会说谎,我是新手,但我对此很感兴趣。我感谢支持! –
'myMonth + = MikeCAT
你重载了前缀运算符,但是'main'中的代码试图调用后缀版本 –