为什么operator <是非成员函数?

abc*_*987 0 c++ operator-overloading

我记得应该C++ Primer告诉我们,而且我始终遵守这条规则.但现在我想知道原因.operator<non-member function

我写了以下代码:

#include <iostream>
using std::cout;
using std::endl;

struct Point1
{
  int x, y;
  Point1(const int a, const int b): x(a), y(b) { }
};
inline bool operator<(const Point1& lhs, const Point1& rhs)
{
  return lhs.x < rhs.x || (lhs.x == rhs.x && lhs.y < rhs.y);
}

struct Point2
{
  int x, y;
  Point2(const int a, const int b): x(a), y(b) { }
  bool operator<(const Point2& rhs)
  {
    return x < rhs.x || (x == rhs.x && y < rhs.y);
  }
};

int main()
{
  Point1 a(1, 2), b(1, 3);
  cout << (a < b) << " " << (b < a) << endl;
  Point2 c(2, 3), d(2, 4);
  cout << (c < d) << " " << (d < c) << endl;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,似乎它们没有区别,member功能似乎更简单.

但在这种情况下:

#include <iostream>
using std::cout;
using std::endl;

 // Usually I write it for comparing floats
class Float1
{
  long double _value;
public:
  static const long double EPS = 1e-8;
  Float1(const long double value): _value(value) { }
  const long double Get() const { return _value; }
};
inline bool operator<(const Float1& lhs, const Float1& rhs)
{
  return rhs.Get() - lhs.Get() > Float1::EPS;
}
inline bool operator<(const Float1& lhs, const long double rhs)
{
  return rhs - lhs.Get() > Float1::EPS;
}

class Float2
{
  long double _value;
public:
  static const long double EPS = 1e-8;
  Float2(const long double value): _value(value) { }
  const long double Get() const { return _value; }
  bool operator<(const Float2& rhs)
  {
    return rhs._value - _value > Float2::EPS;
  }
  bool operator<(const long double rhs)
  {
    return rhs - _value > Float2::EPS;
  }
};

int main()
{
  Float1 x(3.14);
  Float2 y(2.17);
  long double zero = .0;
  cout << (x < zero) << " " << (zero < x) << endl;
  //cout << (y < zero) << " " << (zero < y) << endl; Compile Error!
}
Run Code Online (Sandbox Code Playgroud)

(x <零)和(零<x)都有效!(long double转换成Float?)

但是(零<y)不,因为零不是Float.

在第一种情况下,您会看到member function代码长度减少,而在第二种情况下,non-member function使比较更容易.所以我想知道

  • 在第一种情况下,我应该使用member function而不是non-member function
  • 为什么C++ Primer建议binary operatorS为non-member function
  • 还有其他案例member function并且non-member function有所不同吗?

谢谢你的帮助!

Lil*_*ard 5

我认为基本的答案是非成员函数在隐式转换时更好.因此,如果您可以将二元运算符编写为非成员函数,则应该.