考虑非静态成员函数的 operator== 重载

mah*_*ood 4 c++ operator-overloading

我已经定义了一个这样的类

using namespace std;
class foo {
public:
  typedef std::pair< int, int > index;
  bool operator == ( const index &l, const index &r )
  {
    return (l.first == r.first && l.second == r.second);
  }
  void bar()
  {
    index i1;
    i1.first = 10;
    i1.second = 20;
    index i2;
    i2.first = 10;
    i2.second = 200;
    if (i1 == i2)
       cout << "equal\n";
  }
};
Run Code Online (Sandbox Code Playgroud)

但是我在 Windows 中收到此错误

error C2804: binary 'operator ==' has too many parameters
Run Code Online (Sandbox Code Playgroud)

而这个错误在 linux 中

operator==(const  std::pair<int, int>&, const std::pair<int, int>&)’ must take exactly one argument
Run Code Online (Sandbox Code Playgroud)

我发现这个主题重载 operator== 抱怨“必须只采用一个参数”,并且似乎是类中静态和非静态函数的问题。但是不知道怎么申请this

例如,这是不正确的

  bool operator == ( const index &r )
  {
    return (this->first == r.first && this->second == r.second);
  }
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Naw*_*waz 5

operator==可以通过两种方式实现:

  • 作为成员函数:在这种情况下,函数接受一个参数并在左操作数上调用,该操作数作为this指针隐式传递给函数。
  • 作为非成员函数,在这种情况下,函数接受两个参数,左操作数和右操作数。

由于您正在实现operator==for std::pair,因此您不能将其实现为成员函数( of std::pair)。剩下的选项是非成员函数。

所以在类外实现它:

bool operator==(std::pair<int,int> const & l, std::pair<int,int> const & r)
{
    return (l.first == r.first && l.second == r.second);
}
Run Code Online (Sandbox Code Playgroud)

但是你真的不需要自己实现它,除非你想以不同的方式实现它。该标准库已经提供了一个通用版本operator==用于std::pair其在一对值按字母顺序比较,像我上面那样,即比较firstfirstsecond使用second。如果您需要对它们进行不同的比较,则只有提供您自己的特定定义(非模板版本)。

上面提到的几点值得注意,关于如何operator==在定义的类型需要时实现。

  • 不过请不要这样做。`std::pair` 已经有一个通用的 `operator==` 重载来做明智的事情(第一次与第一次比较,第二次与第二次比较)。只需创建自己的包含两个整数的结构,而不是作为 `std::pair&lt;int,int&gt;` 的 typedef。 (2认同)