我可以在类中重载静态运算符吗

Can I overload static operator in a class?

本文关键字:静态 运算符 重载 我可以      更新时间:2023-10-16

在C#中,要重载诸如"+"、"-"等运算符,我必须使函数成为类的静态成员:

class MyType
{
   /*...*/
   public static MyType operator+ (MyType a, MyType b)
   {
       MyType ret;
       /* do something*/
       return ret;
   }
}

据我所知,在C++中,这就是我如何重载运算符的方法:

class MyType
{
   /*...*/
public:
   MyType operator+ (MyType b) // *this is the first operand
   {
       MyType ret;
       /* do something*/
       return ret;
   }
};

问题是*this是第一个操作数,因此第一个操作的类型必须是MyType。例如,如果我想将MyType添加到一个整数:

MyType a, b;
b = a + 1;  // Valid
b = 1 + a;  // Error

在C#中,我可以为每种情况重载"+"运算符。

我的问题是:我能在C++中像在C#中一样使用静态运算符吗?据我所知,有一种方法可以做到这一点,使用友元运算符,但在继承函数时会丢失它们。

使左侧intoperator+重载为自由函数,而不是MyType:的成员函数

class MyType
{
  ...
  // MyType + int can be a member function because MyType
  // is the type of the sum's left hand side
  MyType operator+(int rhs) const;
};
// int + MyType needs to be a free function because
// int is the type of the sum's left hand side
MyType operator+(int lhs, const MyType &rhs);

另一个常见的习惯用法是使重载成为感兴趣类的friend。现在,您可以用相同的方式实现这两种情况:

class MyType
{
  ...
  friend MyType operator+(int lhs, const MyType &rhs)
  {
    // get access to MyType's private members here
    // to implement the sum operation
    ...
  }
  friend MyType operator+(const MyType &lhs, int rhs)
  {
    // you can also implement the symmetric case
    // of int on the right hand side here
    ...
  }
};

请注意,尽管operator+重载看起来像第二个示例中的成员函数,但由于它们声明为MyTypefriends,因此它们实际上是全局范围内的自由函数。

您可以在C++中的全局作用域中定义运算符,例如

MyType operator+ (const MyType& a, const MyType& b)
{
    MyType ret;
       /* do something*/
    return ret;
}

如果操作员应该访问类的私有成员,则可能需要向MyType添加友元声明。