【问题标题】:Operator Overloading in C++ as int + objC++ 中的运算符重载为 int + obj
【发布时间】:2010-11-14 09:14:54
【问题描述】:

我有以下课程:-

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));

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

【问题讨论】:

    标签: c++ operators operator-overloading operator-keyword


    【解决方案1】:

    在类外实现运算符重载:

    class Num
    {
    public:
        Num(int i)
        {
            this->i = i;
        }
    
        int i;
    };
    
    int operator+(int i, const Num& n)
    {
        return i + n.i;
    }
    

    【讨论】:

    • +1。无论如何,您应该更喜欢非会员版本,即使在没有必要的情况下也是如此。仅在必要时使用成员变体。
    • 我总是喜欢和我的非会员运营商交朋友。
    【解决方案2】:

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

    int operator+( int lhs, const myclass& rhs ) {
        return lhs + (int)rhs;
    }
    

    【讨论】:

      【解决方案3】:

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

      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' 是明智的。

      【讨论】:

      • 但是不能保证从 int 转换是一个有意义的操作。与仅定义 operator+(int, Num) 相比,隐式对话可能效率低下
      • @jalf:添加转换的警告。关于隐式转换,如果函数是内联的,那么一个好的编译器应该为上述生成与 (int, Num) 情况相同的代码。
      • 感谢您的回答,我的问题是:在 operator+= 中您给出的输入是 Num 类型的对象,但是如果我想添加一个整数呢? (我的 g++ 说我需要将一个对象作为输入)
      • @Tomer:你在测试什么例子?
      【解决方案4】:

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

      int operator+( int intobj, myclass myobj )
      { return intobj + int(myobj); }
      

      【讨论】:

      • 使用依赖于参数的查找,它不应该是全局的。
      猜你喜欢
      • 2016-07-22
      • 2020-07-16
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多