为嵌套在 class 中的枚举定义运算符
Defining operators for enums nested within a class
假设我有这个:
class Example {
enum class E { elem1, elem2 };
E& operator++(E& e) {
// do things
}
};
似乎非常有道理,我什至看到它在 other questions 中使用,但编译器告诉我参数只能为空或 int。
这在正常的 class 中是有意义的,但是当我没有 this
值时,我究竟应该做什么?
您在 class 中定义的运算符适用于 class Example
,因此具有参数和 return 类型的 E&
是不正确的,编译器告诉你的。
标准告诉我们:
An operator function shall either be a non-static member function or be a non-member function[...]
它不能是E
的非静态成员函数,因此它必须是非成员函数。
您可以在 Example
之外定义运算符,如下所示:
Example::E& operator++(Example::E& e) {
// modify e
return e ;
}
正如@Shafik 回答的那样,您可以为在 class 内声明的枚举声明运算符,仅作为非成员函数,如下所示:
class Example
{
public:
enum class Element
{
Element1,
Element2
};
};
Example::Element operator++(Example::Element element)
{
// do things
}
有一个很好的 post 关于枚举的增量运算符的实现。希望对你有帮助:)
假设我有这个:
class Example {
enum class E { elem1, elem2 };
E& operator++(E& e) {
// do things
}
};
似乎非常有道理,我什至看到它在 other questions 中使用,但编译器告诉我参数只能为空或 int。
这在正常的 class 中是有意义的,但是当我没有 this
值时,我究竟应该做什么?
您在 class 中定义的运算符适用于 class Example
,因此具有参数和 return 类型的 E&
是不正确的,编译器告诉你的。
标准告诉我们:
An operator function shall either be a non-static member function or be a non-member function[...]
它不能是E
的非静态成员函数,因此它必须是非成员函数。
您可以在 Example
之外定义运算符,如下所示:
Example::E& operator++(Example::E& e) {
// modify e
return e ;
}
正如@Shafik 回答的那样,您可以为在 class 内声明的枚举声明运算符,仅作为非成员函数,如下所示:
class Example
{
public:
enum class Element
{
Element1,
Element2
};
};
Example::Element operator++(Example::Element element)
{
// do things
}
有一个很好的 post 关于枚举的增量运算符的实现。希望对你有帮助:)