加号运算符的 C++ 重载

Sno*_*oot 6 c++ int sum 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;
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*ska 7

你可以像这样改变你的代码,

#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;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助...

  • 这个答案没有解释问题是什么或答案为什么有效。仅由代码组成的答案是不完整的。 (3认同)