【问题标题】:C++ overloading of the plus operator加号运算符的 C++ 重载
【发布时间】:2019-02-21 21:47:39
【问题描述】:

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

【问题讨论】:

  • 作为一个成员函数,它只需要一个参数。
  • 提示:作为非成员函数,它将支持第一个参数,该参数不直接为point,但提供到point 的隐式转换。这对于成员函数是不可能的。因此,定义中缀+ 的首选方法是作为非成员函数。要做到这一点,只需在您已有的定义前面添加friend
  • 如果你已经声明了operator+,它需要在类定义之外
  • 可以在What are the basic rules and idioms for operator overloading?找到关于这个和其他类似主题的许多智慧
  • 参数是引用是可以的,但是它们应该是对const point的引用,以支持右值表达式和const point实际参数。

标签: c++ sum int operator-overloading operator-keyword


【解决方案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;
}

希望这会有所帮助...

【讨论】:

  • 根据 Antoine Morrier 和 user4581301 的 cmets 进行编辑
  • 此答案没有解释问题所在或答案为何有效。仅由代码组成的答案是不完整的。
【解决方案2】:

我得到的 gdb 错误是

main.cpp:8:49: error: ‘point point::operator+(point&amp;, point&amp;)’ 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};
}

【讨论】:

  • "那么你必须把声明放在类之外"。不,我通常更喜欢在类中定义诸如friend 之类的函数。但这取决于,一如既往。
  • 使用你的结构,编译器会抛出这个“错误:没有匹配函数调用'point::point()'|”对我来说,所以它仍然无法正常工作
【解决方案3】:
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;
  }
};

上面有一堆小技巧可以让遵循这种模式成为一个很好的“不费吹灰之力”。

【讨论】:

    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 2017-08-15
    • 2011-12-03
    • 1970-01-01
    • 2012-09-23
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多