C++ 无法在 typedef 结构中重载<运算符

C++ Unable to overload < operator in typedef struct

本文关键字:重载 lt 运算符 结构 typedef C++      更新时间:2023-10-16

我有一个 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<接受一个参数加上一个隐式this1

有了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函数;但是您的原始代码没有显示该技术。