【发布时间】:2016-06-26 07:41:43
【问题描述】:
我在尝试为枚举类重载小于运算符以用于实验目的时遇到问题,但令人惊讶的是,它仅适用于一元运算符,即 ++。编译器抱怨歧义:
enum class Fruit
{
apple,
banana,
orange,
pineapple,
lemon,
};
bool operator<(Fruit l, Fruit r)
{
return true;
}
int main()
{
Fruit f = Fruit::banana;
Fruit a = Fruit::apple;
std::cout << (a < f);
}
编译器显然在全局范围内发现了另一个小于运算符,但为什么它不采用重载的运算符,因为它是完全匹配的呢?
【问题讨论】:
-
我也尝试过 operator
-
我不明白你的担心。你的operator is actually called?
-
为我工作。 ideone.com/GO6HWR.
-
gcc 4.9 和 msvc 2015 都有错误:error C2593: 'operator
-
您是否将程序编译为 C++11 程序?对于
gcc,您需要在命令行中使用-std=c++11。我不知道如何在 VS2015 中启用 C++11 功能。
标签: c++ visual-c++ enums overloading