c++ - 运算符重载 C++

标签 c++ operator-overloading

我正在尝试创建一个程序,要求用户输入一个月。然后程序会显示当月、次月、上月、后五月和前七月。我无法让程序减去一个月或其他后续操作。我只能让它在下个月添加。有什么想法吗?

#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::ostreamoperator<<重载,猜猜“month[month_num]”会为你做什么?

operator++ 变成:

month_num=(month_num+1) % 12;

运算符--变成

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;

等...

关于c++ - 运算符重载 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641461/

相关文章:

c++ - 运算符重载函数无法访问私有(private)成员

c++ - 重载 >> 继承类的运算符

c++ - 覆盖按位运算符时的 MISRA 警告

c++ - 运算符重载 >>

c++ - 使用 Turbo C++,如何在 C 中绘制图形?

c# - 从窗口句柄获取真实文本

c++ - CRTP 和默认赋值运算符

c++ - 为什么无法在堆栈上分配任意大小的数组?

c++ - 使用函数操作文件

c++ - 重载赋值和加运算符