例如,如果我有:
typedef enum { year, month, day } field_type;
inline foo operator *(field_type t,int x)
{
return foo(f,x);
}
inline foo operator -(field_type t)
{
return t*-1;
}
int operator /(distance const &d,field_type v)
{
return d.in(v);
}
因为如果我不定义这样的运算符,那么编写 day*3
实际上是合法的,它
会被翻译成6吗?
那么合法吗?
至少 gcc 和 intel 编译器在没有警告的情况下接受这个。
澄清:
我不想要默认算术运算,我想要返回非整数类型的自己的运算。
最佳答案
是的,可以对枚举和类类型进行运算符重载。你这样做的方式很好,但你应该使用+
促进枚举,而不是 *-1
或其他东西(最终目的是避免无限递归,因为 -t
):
inline foo operator -(field_type t) {
return -+t;
}
这将很好地扩展到其他操作。 +
会将枚举提升为可以表示其值的整数类型,然后可以申请-
不会导致无限递归。
请注意,您的 operator*
只允许你做enum_type * integer
,但反之则不然。另一个方向可能也值得考虑。
还要注意,为内置运算符已经接受的操作数重载运算符总是有点危险(即使只是通过隐式转换)。想象一下 distance
有一个转换构造函数采用 int (如 distance(int)
),然后给出你的 operator/
以下是模棱两可的
// ambiguous: operator/(int, int) (built-in) or
// operator/(distance const&, field_type) ?
31 / month;
为此,也许最好制作field_type
具有适当运算符的真实类,以便您可以从开始时排除任何此类隐式转换。 C++0x 的enum class
提供了另一个很好的解决方案。 ,它提供了强大的枚举。
关于c++ - 我可以在 C++ 中的枚举类型上重载运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2393439/