C++结构体定义operator==报C2804、C2333编译错误如何解决?
错误成因
- 二元运算符
operator==作为结构体的成员函数实现时,会自动携带隐式的this指针作为左操作数,仅需传入1个右操作数参数即可。你当前的成员函数实现写了2个显式参数,加上隐式的this总共3个参数,不符合二元运算符的参数数量要求,因此触发C2804报错,连带导致函数体无法正常编译触发C2333报错。
修复方案
共有两种合规的实现方式,均可正常支持QList的元素比较逻辑:
方案1:成员函数实现(推荐)
仅保留1个右操作数参数,直接通过当前对象的成员与右操作数比较,建议添加const修饰保证const正确性:
typedef struct _tBScan { QString strQuadpackNumbers; uint uintBegin, uintEnd; bool operator==(const struct _tBScan& b) const { return (strQuadpackNumbers == b.strQuadpackNumbers && uintBegin == b.uintBegin && uintEnd == b.uintEnd); } } tBScan;
方案2:全局/友元函数实现
如果要保留双参数的写法,可将运算符实现移到结构体外部,可选声明为友元(结构体默认成员公开时可省略友元声明):
typedef struct _tBScan { QString strQuadpackNumbers; uint uintBegin, uintEnd; friend bool operator==(const _tBScan& a, const _tBScan& b); } tBScan; bool operator==(const _tBScan& a, const _tBScan& b) { return (a.strQuadpackNumbers == b.strQuadpackNumbers && a.uintBegin == b.uintBegin && a.uintEnd == b.uintEnd); }
内容的提问来源于stack exchange,提问作者SPlatten
相关产品推荐
相关产品推荐

