美文网首页
关于运算符重载(2.1)

关于运算符重载(2.1)

作者: Raaa_bit | 来源:发表于2019-02-01 18:42 被阅读0次
       Box operator+(const Box& b)
       {
          Box box;
          box.length = this->length + b.length;
          box.breadth = this->breadth + b.breadth;
          box.height = this->height + b.height;
          return box;
       }
    

    this为运算符前对象,b为运算符后对象。
    如:
    Box3 = Box1 + Box2;
    Box1为this,Box2为b。
    也由此可知,运算符重载中传入参数只能放于运算符后。
    因此,对于想改变运算顺序的运算符重载,必须使用友元函数。
    而使用友元函数时,也要注意:

    当重载为成员函数时,会隐含一个this指针;当重载为友元函数时,不存在隐含的this指针,需要在参数列表中显示地添加操作数。

    参考资料:

    runoob
    CSDN

    相关文章

      网友评论

          本文标题:关于运算符重载(2.1)

          本文链接:https://www.haomeiwen.com/subject/ixidsqtx.html