c++ - 如何重载 operator< 以将对象放入集合中

标签 c++ set operators operator-overloading

我想将对象放入集合中,据我所知,我需要为此重载运算符<。所以我想到了这样的事情:

   bool Client::operator< (Category &cC1, Category &cC2){
      return cC1.getName() < cC2.getName();
   }

   // Setters----------------------------------------------------------------
   void Client::addNewCategory(const string &categName){
      Category cat(categName);
      i->categoriesMap.insert(i->categoriesMapPos++, cat);
   }

i 是指向定义了 set categoriesMap 及其迭代器的内部类的指针。

所以我重载了运算符<,但它仍然不起作用,我得到一个错误,运算符有太多参数(但是我如何比较没有两个对象的对象)?另外,我收到错误 5 IntelliSense: class "ExpenseManagerNamespace::Client" has no member "operator<"我使用 visual studio 2013。

最佳答案

使运算符成为免费(非成员)函数:

bool operator< (Category const& cC1, Category const& cC2){
   return cC1.getName() < cC2.getName();
}

如果getName,您可能需要为该函数提供友元。不公开。

operator<的成员函数版本用于将其他对象与 this 进行比较.这可能不是你想要的,因为 this类型为 Client在你的情况下,你似乎想比较两个 Category

关于c++ - 如何重载 operator< 以将对象放入集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20243816/

相关文章:

c++ - std::set 和 < 运算符重载的奇怪行为?

php - PHP 中有数学集的表示吗?

javascript - 正确的 JavaScript 运算符优先级表是什么?

c - C : how this function works? 中的按位运算符

c++ - 如何在二维数组中绘制 X? C++

c++ - 找到一个矩形与另一个矩形接触的边

c# - 你能中止一个属性(property)的设定程序吗

python - boost python raw_function 方法

c++ - 'to_string' 不是 'std' 的成员

c++ - 按值显式复制构造函数或隐式参数