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

时间:2015-06-05 16:56:52

标签: c++ class operator-overloading overloading

我正在学习C ++,当我做了一个小程序来了解更多关于运算符重载的程序时,程序在主函数中给出了一个错误,我写了" Ponto p1( 1,5),p2(3,4),Soma;" 。任何人都可以解释我如何正确使用运营商Overloagin 吗?谢谢。

PS:该程序采用我的母语Portugueses,但我认为找到我的错误不会有问题。

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

2 个答案:

答案 0 :(得分:2)

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

一旦提供了自己的构造函数,就不再生成编译器提供的默认构造函数。您必须自己创建或者在构造函数的参数上添加默认值。

答案 1 :(得分:2)

您应该使用某些值初始化Ponto SomePonto Some = p1 + p2;

此外,您应该将"constant reference" - reference to const objectconst 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;
}
相关问题