加号运算符的C ++重载

时间:2018-09-17 22:59:57

标签: c++ sum int operator-overloading operator-keyword

我想通过重载+运算符来添加2个对象,但我的编译器表示没有可调用point :: point(int,int)的匹配函数。有人可以帮我这个代码,并解释错误吗?谢谢

#include <iostream>

using namespace std;

class point{
int x,y;
public:
  point operator+ (point & first, point & second)
    {
        return point (first.x + second.x,first.y + second.y);
    }
};

int main()
{
    point lf (1,3)
    point ls (4,5)
    point el = lf + ls;
    return 0;
}

3 个答案:

答案 0 :(得分:2)

我得到的gdb错误是

main.cpp:8:49: error: ‘point point::operator+(point&, point&)’ must take either zero or one argument

这是因为您要对其执行操作的对象是this(左侧),然后右侧是自变量。如果您希望使用所采用的格式,则可以将声明放在类之外-即

struct point
{
  // note made into a struct to ensure that the below operator can access the variables. 
  // alternatively one could make the function a friend if that's your preference
  int x,y;
};

point operator+ (const point & first, const point & second) {
  // note these {} are c++11 onwards.  if you don't use c++11 then
  // feel free to provide your own constructor.
  return point {first.x + second.x,first.y + second.y};
}

答案 1 :(得分:1)

您可以像这样更改代码,

#include <iostream>

using namespace std;

class point {
    int x, y;
public:
    point(int i, int j)
    {
        x = i;
        y = j;
    }

    point operator+ (const point & first) const
    {
        return point(x + first.x, y + first.y);
    }

};

int main()
{
    point lf(1, 3);
    point ls(4, 5);
    point el = lf + ls;

    return 0;
}

希望这对您有帮助...

答案 2 :(得分:0)

class point{
  int x,y;
public:
  point& operator+=(point const& rhs)& {
    x+=rhs.x;
    y+=rhs.y;
    return *this;
  }
  friend point operator+(point lhs, point const& rhs){
    lhs+=rhs;
    return lhs;
  }
};

上面有许多小技巧,使遵循此模式成为一个“精明的头脑”。