运算符重载 - (前缀)

时间:2015-03-06 20:33:02

标签: c++

我尝试过载operator--前缀,但我有错误,有人求助吗?

#include <iostream>
#include "Circulo.h"

using namespace std;

int main()
{
    //parametrizado
    Circulo c1(10.5, 20.0, 1, "Rojo Intenso"),c2, c3;
/*
    c2 = c1--;    // decrementa, si se puede, el diámetro

    c3 = c2++;    // incrementa, si se puede, el diámetro

    Circulo c4 = c3++;

    c4.CambiarColor("Amarillo patito flúo");


    cout << c1 << c2 << c3 << (c4 = c3) << endl;
*/
    return 0;
}

Circulo.cpp

#include "Circulo.h"
#include <string.h>

using namespace std;

Circulo :: Circulo() //por defecto
{
    x=5.0;
    y=6.0;
    diam=50;
    strcpy(Color,"Rojo");
}

Circulo::Circulo(float x,float y,unsigned diam,char *Color) //parametrizado
{
    this->x=x;
    this->y=y;
    this->diam=diam;
    this->Color= Color;
}

Circulo::Circulo(const Circulo& obj) //por copia
{
    this->x=obj.x;
    this->y=obj.y;
    this->diam=diam;
    this->Color=Color;
}

Circulo :: operator--(const Circulo &obj)const
{
    Circulo aux(this->real+obj.x);
    return aux;
}

Circulo.h

#ifndef CIRCULO_H
#define CIRCULO_H
#include <iostream>

using namespace std;

class Circulo
{
    public:
        Circulo();
        Circulo(float x,float y,unsigned diam,char *Color);
        Circulo(const Circulo& obj);
        Circulo operator --(const Circulo &obj) const;
    private:
        float x,y;
        unsigned diam;
        char *Color;

};

#endif // CIRCULO_H

错误:postfix&#39; Circulo Circulo :: operator - (const Circulo&amp;)const&#39;必须采取&#39; int&#39;作为其论点

C:\Documents and Settings\laboratorios\Mis documentos\Clase Circulo\Circulo.h|13|error: postfix 'Circulo Circulo::operator--(const Circulo&) const' must take 'int' as its argument|
C:\Documents and Settings\laboratorios\Mis documentos\Clase Circulo\Circulo.cpp|30|error: ISO C++ forbids declaration of 'operator--' with no type [-fpermissive]|
C:\Documents and Settings\laboratorios\Mis documentos\Clase Circulo\Circulo.cpp|30|error: postfix 'int Circulo::operator--(const Circulo&) const' must take 'int' as its argument|
||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|

1 个答案:

答案 0 :(得分:3)

当您重载作为成员函数的运算符(而不是friend)时,您不需要指定其参数。

Circulo operator --(const Circulo &obj) const;

应该是

Circulo operator --(); // probably not const, since you modify the instance

该错误告诉您编译器需要(虚拟)int,这是编译器用来实现您想要定义后缀operator--()的惯例,

Circulo operator --(int); // dummy int, convention postfix

有关运算符重载的最佳指南之一,请参阅Operator overloading(一元算术运算符)。

您可以在当前实例上调用这些运算符,例如

Circulo c;
--c; // same as c.operator--();

因此无需指定参数。

此外,您的实现不正确(感谢@Praetorian),您不需要复制该对象,而是直接修改实例,然后返回对*this的引用(对于前缀{{1 }})。