我正在用 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)
in operator/
, (~i)
returns Imaginary
这是一个右值。您无法将该右值绑定到 lavue 引用,因此不会考虑您的重载,并且您会收到编译器错误。
解决这个问题最简单的方法是采取const &
相反喜欢
Imaginary Imaginary::operator*(const Imaginary &i)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)