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

时间:2012-09-06 07:02:11

标签: c++ operator-overloading

在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#相同的方法,使用静态运算符吗?据我所知,有一种方法可以与朋友操作员一起完成,但是在继承函数时它们会丢失。

2 个答案:

答案 0 :(得分:3)

您可以在C ++中定义全局范围内的运算符,例如

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

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

答案 1 :(得分:3)

使operator+重叠,并在左侧使用int自由函数而不是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+重载看起来像第二个示例中的成员函数,它们实际上是自由函数,因为它们声明为friend的{​​{1}}而存在于全局范围内}。

相关问题