我有一个奇怪的问题,为我的一个班级定义 ==。我将此处的代码简化为我在 Visual 2013 上测试的示例; MyClass 在命名空间 N 中定义
这确实编译:
N::MyClass a, b;
bool test = a == b;
这个也是:
const N::MyClass a, b;
bool test = a == b;
这不编译
std::map<int, N::MyClass> a, b;
bool test = a == b;
供您参考, == 运算符声明如下:
bool operator==(const N::MyClass & a, const N::MyClass & b);
这是我得到的错误:error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const MyClass' (or there is no acceptable conversion)
但据我所知,map 运算符是定义的:map == reference on cppreference.com
有人可以解释一下为什么这是错误的吗?
先感谢您。
我没有找到答案,如果这是愚蠢的,我很抱歉。
[解决方案] 如果我将操作员模式化到命名空间中,它可以工作:
bool N::operator==(const MyClass & a, const MyClass & b);
但我不知道为什么我需要这样做,是在语言定义中吗? (我猜是)