use*_*354 -1 c++ struct typedef operator-overloading
我有一个像这样定义的typedef结构:
typedef struct myStruct {
int id;
double value;
bool operator <(const myStruct &x, const myStruct &y) {
return (x.id < y.id);
}
} myStruct;
Run Code Online (Sandbox Code Playgroud)
我需要将此结构用作std :: map中的键,从而重载运算符.但是,我在尝试编译时收到以下错误消息:
overloaded 'operator<' must be a binary operator (has 3 parameters)
Run Code Online (Sandbox Code Playgroud)
好的,所以我尝试了这个:
bool operator <(const pointcloud_keyframe &x) {
return (this->id < x.id);
}
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用,因为我在尝试插入地图时收到此错误消息:
invalid operands to binary expression ('const myStruct' and 'const myStruct')
Run Code Online (Sandbox Code Playgroud)
请帮忙!
struct myStruct {
int id;
double value;
friend bool operator <(const myStruct &x, const myStruct &y) {
return (x.id < y.id);
}
};
Run Code Online (Sandbox Code Playgroud)
关键部分是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);
}
Run Code Online (Sandbox Code Playgroud)
但是<
一个friend
是相对无害的.此外,对于template
类型,朋友策略可以更好地扩展.所以我习惯使用它,即使技术上"权限越少越好".
1我发现这个令人讨厌的不对称,所以我更喜欢非<
会员<
.
归档时间: |
|
查看次数: |
596 次 |
最近记录: |