运算符重载C++
Operator Overloading 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;
运算符 -- 变为
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++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 正在尝试重载二进制搜索树分配运算符
- 重载Singly Linked List中的赋值运算符
- 取消引用运算符不能重载