17

我有以下课程:-

class myclass
{
    size_t st;

    myclass(size_t pst)
    {
        st=pst;
    }

    operator int()
    {
        return (int)st;
    }

    int operator+(int intojb)
    {
        return int(st) + intobj; 
    }

};

只要我这样使用它就可以正常工作:-

char* src="This is test string";
int i= myclass(strlen(src)) + 100;

但我无法做到这一点: -

int i= 100+ myclass(strlen(src));

任何想法,我怎么能做到这一点?

4

4 回答 4

26

在类外实现运算符重载:

class Num
{
public:
    Num(int i)
    {
        this->i = i;
    }

    int i;
};

int operator+(int i, const Num& n)
{
    return i + n.i;
}
于 2009-07-27T14:49:10.090 回答
12

您必须将运算符实现为非成员函数以允许左侧的原始 int 。

int operator+( int lhs, const myclass& rhs ) {
    return lhs + (int)rhs;
}
于 2009-07-27T14:50:40.557 回答
4

这里的其他答案将解决问题,但以下是我这样做时使用的模式:

class Num
{
public:
  Num(int i)       // Not explicit, allows implicit conversion to Num
  : i_ (i)
  {
  }

  Num (Num const & rhs)
  : i_ (rhs.i_)
  {
  }

  Num & operator+= (Num const & rhs)  // Implement +=
  {
    i_ += rhs.i_;
    return *this;
  }

private:
    int i_;
};

//
// Because of Num(int), any number on the LHS or RHS will implicitly
// convert to Num - so no need to have lots of overloads
Num operator+(Num const & lhs, Num const & rhs)
{
  //
  // Implement '+' using '+='
  Num tmp (lhs);
  tmp+=rhs;
  return tmp;
}

这种方法的主要好处之一是您的功能可以相互实现,从而减少您需要的整体代码量。

更新:

为了避免性能问题,我可能会将非成员 operator+ 定义为内联函数,例如:

inline Num operator+(Num lhs, Num const & rhs)
{
  lhs+=rhs;
  return lhs;
}

成员操作也是内联的(因为它们是在类主体中声明的),因此在所有代码中应该非常接近添加两个原始int对象的成本。

最后,正如 jalf 所指出的,通常需要考虑允许隐式转换的后果。上面的示例假定从整数类型转换为“Num”是明智的。

于 2009-07-27T15:03:25.107 回答
2

您需要一个全局函数 operator+( int, myclass ) 来执行此操作:

int operator+( int intobj, myclass myobj )
{ return intobj + int(myobj); }
于 2009-07-27T14:49:10.963 回答