C++加号运算符的重载

C++ overloading of the plus operator

本文关键字:重载 运算符 C++      更新时间:2023-10-16

我想通过重载 + 运算符来添加 2 个对象,但我的编译器说没有匹配的函数可以调用 point::p oint(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;
}

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

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

希望这有帮助...

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

上面有一堆小技巧,使遵循这种模式成为一个很好的"不费吹灰之力"。

  1. 您可以通过"正确"的语义获得+=+
  2. 如果将+链接在一起,则会省略左侧操作。 (即,a+b+c变为(a+b)+ca+b的返回值被省略到_+c调用中(。 如果对象具有可移动状态,则无需设计成本即可进行正确的移动。
  3. 如果abpoint,而另一个具有隐式转换为point,则a+b工作。 如果a不是重点,则成员operator+不这样做;这是毫无意义的不对称。
  4. a+=b实施通常比a=a+b更有效。 当您在此处实现+=时,您也会获得高效的+。 而你的+=又是根据成员变量+=s 来定义的。

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