VS2010编译C++代码报C2678错误,重载AnyColor类==运算符仍未识别
问题核心原因
- 你定义的
operator==是类的非const成员函数,隐含的this指针没有const修饰,无法在const类型的AnyColor对象上调用。而unordered_map的键值默认是const修饰的,执行比较操作时左操作数为const对象,无法匹配你写的运算符函数。 - 自定义类型作为
unordered_map的键,必须提供对应的哈希函数实现,标准库没有为AnyColor提供默认哈希规则,缺少这部分也会编译报错。 operator!=的参数缺少const修饰,也没有声明为const成员函数,同样存在匹配问题。
具体修改步骤
1. 修改比较运算符的声明
给operator==和operator!=都添加const修饰,同时修正operator!=的参数为const引用:
// 所有成员相等时判定为相等,末尾加const表示不会修改当前对象 inline bool operator==(const AnyColor& op) const { if (space != op.space) { return false; } for(int i = 0; i <4; i++) { if (axis[i] != op.axis[i]) { return false; } } return true; } // 参数加const,函数本身加const inline bool operator!=(const AnyColor &op) const { return !(*this == op); }
2. 实现AnyColor的哈希函数
在AnyColor类定义的外部、全局作用域中,特化std::hash模板:
namespace std { template<> struct hash<AnyColor> { size_t operator()(const AnyColor& c) const { // 兼容VS2010的哈希组合逻辑 size_t h = hash<cSpace>()(c.space); h ^= hash<double>()(c.axis[0]) + 0x9e3779b9 + (h << 6) + (h >> 2); h ^= hash<double>()(c.axis[1]) + 0x9e3779b9 + (h << 6) + (h >> 2); h ^= hash<double>()(c.axis[2]) + 0x9e3779b9 + (h << 6) + (h >> 2); h ^= hash<double>()(c.axis[3]) + 0x9e3779b9 + (h << 6) + (h >> 2); return h; } }; }
3. 可选优化unordered_map声明
原有声明中键的const修饰可以去掉,unordered_map内部会自动将键处理为const类型,修改为:
static std::unordered_map<AnyColor,int> colormap;
修改完成后即可正常编译运行,符合VS2010的C++11特性支持范围。
内容的提问来源于stack exchange,提问作者Logicrat
相关产品推荐
相关产品推荐

