加号运算符的 C++ 重载

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

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

最佳答案

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

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

希望这有助于...

关于加号运算符的 C++ 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376716/

相关文章:

C++17 std::G++ 中的可选?

c++ - 结构数组在调用时打印零,但在未调用时显示正确的输入(短代码)

java - 求斐波那契数列中小于或等于该数字的所有数字之和

matrix - Octave:求和除第一列之外的所有元素?

c - 如何使用直接来自函数的返回值作为位串而不是格式化数字?

c - 如何在 1990 年的 const 定义中添加 2 个整数?

c++ - [basic.lookup.unqual]/3 中的第一个示例

c++ - 通过引用传递的二维 vector 的就地转置

mysql - 如何获取 GROUP_CONCAT(if(type = 'tax' ,amount,NULL)) AS 'tax' 返回的逗号分隔值的总和

Java:如何比较两个 int[] 数组中的非重复元素?