加号运算符的 C 重载

新手上路,请多包涵

我想通过重载 + 运算符来添加 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;
}

原文由 Snowshoot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 403
2 个回答

您可以像这样更改代码,

 #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;
}

希望这可以帮助…

原文由 Chathura Dhanuska 发布,翻译遵循 CC BY-SA 4.0 许可协议

我得到的 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};
}

原文由 UKMonkey 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题