[英]Operator overloading for enum increment
I have this enum, and I simply want to increment an object of that enum by one place. 我有这个枚举,我只想将该枚举的对象增加一个位置。
enum Month {
january = 1,
february,
march,
april,
may,
june,
july,
august,
september,
october,
november,
december
};
With the object of my enum, Month m, I simply want to move the object's variable by one position. 对于我的枚举对象Month m,我只想将对象的变量移动一个位置。
Month operator++(Month &m) {
m = static_cast<Month>(m + 1);
return m;
}
With Month &m as the parameter I get error that it needs to take int as an argument. 使用Month&m作为参数,我得到一个错误,需要将int作为参数。 So if I do "(Month &m, int)" it says that it "must take either zero or one arguments." 因此,如果我执行“((Month&m,int)”,则表示“必须接受零个或一个参数”。 I read that you don't need Month &m if your operator overload is a member function, so I removed it. 我读到,如果您的运算符重载是成员函数,则不需要Month&m,因此我将其删除。 After that, I get yet another error: "no match for 'operator++' (operand type is 'Month')". 之后,我又收到另一个错误:“'operator ++'不匹配(操作数类型为'Month')”。 Is there something I am missing? 我有什么想念的吗?
Main code: 主要代码:
class Date {
int y, d, month_end; // private
Month m;
public:
Date(int yy, Month mm, int dd)
: y(yy), d(dd), m(mm) {
}
Month& operator++(Month &m) {
m = static_cast<Month>(m + 1);
return m;
}
void add_month() {
++m;
}
In a comment, you said: 在评论中,您说:
Is there something I'm overlooking? 我有什么要注意的吗? http://ideone.com/uOkSk0 http://ideone.com/uOkSk0
Yes. 是。 You are defining the function in an unusual place -- inside the definition of Date
. 您正在一个不寻常的地方定义函数-在Date
的定义内。 It needs to be a non-member function. 它必须是非成员函数。
using namespace std; 使用名称空间std;
enum Month {
january = 1,
february,
march,
april,
may,
june,
july,
august,
september,
october,
november,
december
};
Month& operator++(Month &m) {
m = static_cast<Month>(m + 1);
return m;
}
class Date {
int y, d;
Month m;
public:
Date(int yy, Month mm, int dd) // constructor
: y(yy), d(dd), m(mm) { // member initializer
}
void add_month() {
++m;
}
};
int main()
{
Month m = january;
++m;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.