C ++ перегрузка оператора плюс - PullRequest
0 голосов
/ 18 сентября 2018

Я хочу добавить 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 голосов
/ 18 сентября 2018

Вы можете просто изменить свой код следующим образом,

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

Надеюсь, это поможет ...

0 голосов
/ 18 сентября 2018
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;
  }
};

Есть куча маленьких трюков, которые делают следование этой схеме хорошим "легким делом".

0 голосов
/ 18 сентября 2018

Ошибка с 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};
}
...