加号运算符的C ++重载

问题描述 投票:1回答:3

我想通过重载+运算符来添加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;
}
c++ sum int operator-overloading operator-keyword
3个回答
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
投票

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

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

上面有一堆小技巧,使这种模式成为一个很好的“没脑子”。

© www.soinside.com 2019 - 2024. All rights reserved.