gpt4 book ai didi

c++ - 我如何从同一类中的另一个运算符重载成员函数调用运算符重载成员函数(或使用运算符)?

转载 作者:太空狗 更新时间:2023-10-29 21:34:26 24 4
gpt4 key购买 nike

我正在用 C++ 编写代码来处理复数。我也在练习运算符重载。所以我重载了*(乘法运算符),现在我想在重载的/(除法运算符)中使用重载的运算符,但是当我使用* 显示错误。这是代码:

#include <iostream>
#include <cmath>

using namespace std;

class Imaginary
{
public:
//constructors
Imaginary(double a,double b):x(a),y(b){}
Imaginary():x(0.0),y(0.0){}

//setter methods for x and y
void Setx(double x) { this->x = x; }
void Sety(double y) { this->y = y; }

//getter methods for x and y
double Getx(){return this->x;}
double Gety(){return this->y;}

//overloaded operators
Imaginary operator+(Imaginary&);
Imaginary operator-(Imaginary&);
Imaginary operator*(Imaginary&);
Imaginary operator~();
Imaginary operator/(Imaginary&);

void print();
private:
double x;
double y;
};

Imaginary Imaginary::operator+(Imaginary &i){
Imaginary ti;
ti.Setx(this->x+i.x);
ti.Sety(this->y+i.y);

return ti;
}

Imaginary Imaginary::operator-(Imaginary &i){
Imaginary ti;
ti.Setx(this->x-i.x);
ti.Sety(this->y-i.y);
return ti;
}

Imaginary Imaginary::operator*(Imaginary &i){
Imaginary ti;
ti.Setx((this->x*i.x) - (this->y*i.y));
ti.Sety((this->y*i.x)+(this->x*i.y));
return ti;
}

Imaginary Imaginary::operator~(){
int y;
y = this->y;
this->y = -y;
return *this;
}

Imaginary Imaginary ::operator/(Imaginary &i){
Imaginary numerator,denominator,ti;
//i want to use here the overloaded *(multiplacation) operator
numerator = (*this) * (~i);//showing error
denominator = (*this) * (~i);//showing error
ti.Setx(numerator.Getx()/denominator.Getx());
ti.Sety(numerator.Gety()/denominator.Getx());

return ti;
}

void Imaginary::print(){
cout<<x;
if (y>0)
cout<<"+i"<<y<<endl;
else if (y<0)
cout<<"-i"<<abs(y)<<endl;

}

int main()
{
Imaginary res;
Imaginary z1(2,3);
Imaginary z2(1,-1);
z1.print();
z2.print();

/*res = z1+z2;
cout<<"Addition:-\n";
res.print();

res = z1-z2;
cout<<"Subtraction:-\n";
res.print()*/

res = z1*z2;
cout<<"Multiplication:-\n";
res.print();

res = z1/z2;
cout<<"Division:-\n";
res.print();

return 0;
}

错误信息如下:-

D:\Games\Cheese\main.cpp|66|error: no match for 'operator*' (operand types are 'Imaginary' and 'Imaginary')|

请任何人告诉我如何纠正它。

最佳答案

在这种情况下,错误不是最好的错误。您的 operator* 定义为

Imaginary Imaginary::operator*(Imaginary &i)

这要求右手边是左值。当你做的时候

(*this) * (~i)

operator/ 中,(~i) 返回 Imaginary,它是一个右值。您不能将该右值绑定(bind)到 lavue 引用,因此不会考虑您的重载,并且您会收到编译器错误。

解决这个问题的最简单方法是使用 const & 而不是

Imaginary Imaginary::operator*(const Imaginary &i)

关于c++ - 我如何从同一类中的另一个运算符重载成员函数调用运算符重载成员函数(或使用运算符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549734/

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