gpt4 book ai didi

c++ - 运算符重载--(前缀)

转载 作者:行者123 更新时间:2023-11-28 00:18:15 26 4
gpt4 key购买 nike

我试过重载运算符--前缀,但我有错误,有人帮忙吗?

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

循环.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;
}

循环.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

错误:后缀 'Circulo Circulo::operator--(const Circulo&) const' 必须将 'int' 作为其参数

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) ===|

最佳答案

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

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的引用(对于前缀 operator--()).

关于c++ - 运算符重载--(前缀),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28907161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com