C++ 无法在 typedef 结构中重载<运算符
C++ Unable to overload < operator in typedef struct
我有一个 typedef 结构,定义如下:
typedef struct myStruct {
int id;
double value;
bool operator <(const myStruct &x, const myStruct &y) {
return (x.id < y.id);
}
} myStruct;
我需要将此结构用作 std::map 中的键,因此重载运算符。但是,尝试编译时收到以下错误消息:
overloaded 'operator<' must be a binary operator (has 3 parameters)
好的,所以我尝试了这个:
bool operator <(const pointcloud_keyframe &x) {
return (this->id < x.id);
}
但是,这也不起作用,因为我在尝试插入地图时收到此错误消息:
invalid operands to binary expression ('const myStruct' and 'const myStruct')
请帮忙!
struct myStruct {
int id;
double value;
friend bool operator <(const myStruct &x, const myStruct &y) {
return (x.id < y.id);
}
};
关键部分是friend
. 我还删除了typedef
;在C++ struct myStruct
已经定义了一个名为myStruct
的类型,不需要也typedef
它。
还有其他方法可以使代码编译,但这是最简单的方法。
如果没有friend
,你的operator<
是一个成员函数,成员operator<
接受一个参数加上一个隐式this
。1
有了friend
,它就变成了一个接受2个参数的"自由函数"。 我发现这是最干净的方法。 它仍然具有访问struct
私有位的完全权限(可能不需要(。
您也可以将其移动到struct
本身之外
struct myStruct {
int id;
double value;
};
inline bool operator <(const myStruct &x, const myStruct &y) {
return (x.id < y.id);
}
但<
成为friend
相对无害。 此外,对于template
类型,好友策略的扩展性更好。 所以我习惯于使用它,即使从技术上讲"权限越少越好"。
1 我觉得这很烦人,所以我更喜欢非会员<
而不是会员<
。
鉴于您显示的代码,您非常接近,但并不完全......您需要区分成员函数和独立的"自由"函数。
struct myStruct final { int id; };
inline bool operator<(const myStruct& lhs, const myStruct& rhs) {
return lhs.id < rhs.id;
}
请记住,您应该更喜欢使用非成员函数。
使用成员函数类似,但不如上述函数理想:
class myStruct final
{
int id_;
public:
bool operator<(const myStruct& rhs) const {
return id_ < rhs.id_;
}
};
另一种方法是使operator<()
成为具有各种权衡的friend
函数;但是您的原始代码没有显示该技术。
相关文章:
- C++重载<<具有typedef'd std::vector
- 重载运算符<<:此运算符函数的参数太多
- 在VS 2012上编译,但不使用Netbeans/MinGW-重载<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- C++分离成员流重载<<
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 重载运算符<<用于ostream语法
- 重载operator< & lt;作为会员打印
- Operator< & lt;重载隐藏其他
- 重载& lt; & lt;为什么我得到以下错误
- 重载ostream&时转换错误无效;operator< & lt;
- operator< & lt;在c++中为类中的类重载
- 重载& lt; & lt;用于打印自定义异常的操作符
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多
- 上Ostream & lt; & lt;重载的困惑
- 重载& lt; & lt;为了我的班级
- 使用带有重载<<endl上的运算符
- 重载& lt; & lt;使用命名空间std
- 重载& lt; & lt;错误