运算符重载C++=

operator overloading C++ +=

本文关键字:C++ 重载 运算符      更新时间:2023-10-16

我有class ItemItem itemsint q。我正试图制作一个函数来重载+=。我需要一个朋友功能,还是必须是会员?

主程序中的语句是

             items+=q;

类中项目头文件:

   friend Item operator+=(const Item&, int&);

类中项目cpp文件:

    Item operator+=(const Item& items, int& q)
    {
         items+=q;
         return items;
    }

所以编译器说"+="不匹配

这两种可能性都是可能的。

http://en.cppreference.com/w/cpp/language/operatorshttp://en.cppreference.com/w/cpp/language/operator_assignment(见表)

A+=运算符可以如下返回void:

class Point
{
private:
  int x;
  int y;
public:
  void operator += (const Point& operand)
  {
     this->x += operand.x;
     this->y += operand.y;
  }
};

或者可以返回一个引用:

class Point
{
private:
  int x;
  int y;
public:
  Point& operator += (const Point& operand)
  {
     this->x += operand.x;
     this->y += operand.y;
     return *this;
  }
};

后者是更好的做事方式,因为它允许链接。

更改此项:

Item operator+=(const Item& items, int& q)
    {
         items+=q;
         return items;
    }

Item operator+=(int q)
    {
         this->quanity += q;
         return *this;
    }

当然,这意味着它是班上的一员。。。