C++中运算符重载的语法是什么?

What is the syntax for Operator Overloading in C++?

我正在学习 C++,当我编写了一个小程序来了解更多关于 运算符重载 的程序在我编写 的主函数中给出了一个错误"Ponto p1(1,5), p2(3,4), Soma;"。谁能给我解释一下如何正确使用 Operator Overloagin?谢谢你。

PS: 程序是葡萄牙语,我的母语,但我认为找到我的错误不会有问题。

#include <iostream>

using namespace std;

class Ponto
{
private:
    int x,y;
public:

    Ponto(int a, int b)
    {
       x = a;
       y = b;
    }
    Ponto operator+(Ponto p);
};

Ponto Ponto::operator+(Ponto p)
{
    int a, b;
    a = x + p.x;
    b = y + p.y;

    return Ponto(a, b);
}

int main(void)
{
    Ponto p1(1,5), p2(3,4), Soma; 
    Soma = p1.operator+(p2);
    return 0;
}

您没有默认构造函数,因此当它尝试构造 Soma 时会出现错误。

一旦您提供了自己的构造函数,编译器提供的默认构造函数就不再生成。您要么必须自己创建参数,要么将默认值添加到采用参数的构造函数的参数中。

你应该用一些值初始化 Ponto SomePonto Some = p1 + p2;

您还应该将 "constant reference" - reference to const object: const Ponto &name 传递给运算符+。

所以,固定代码:

#include <iostream>

using namespace std;

class Ponto {
    int x, y;

public:
    Ponto(int, int);
    Ponto operator+(const Ponto&);
};

Ponto::Ponto(int a, int b) : x(a), y(b) {};  // Use 'initializer list'

Ponto Ponto::operator+(const Ponto &other) {
    // Not need to do calculations explicitly
    return Ponto(x+other.x, y+other.y);
}

int main() {
    Ponto p1(1, 5), p2(3, 4);
    // Not need to call operator+ explicitly - it's compiler's work
    Ponto Soma = p1 + p2;
    return 0;
}