比较两个复数的大小和是否相等,用重载运算符的方法写程序?
发布网友
发布时间:2024-10-20 13:51
我来回答
共1个回答
热心网友
时间:2024-11-14 16:42
#include <iostream>
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator+(Complex& );//操作符重载,两复数相加
Complex operator*(Complex& );//操作符重载,丙复数相乘
bool operator==(Complex &); //操作符重载,判断是否相等
double getReal(void) const;//返回实部
double getImag(void) const;//返回虚部
double setReal(double real);//设置实部
double setImag(double imag);//设置虚部
private:
double real;
double imag;
};
Complex Complex::operator+(Complex& c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
Complex Complex::operator*(Complex& c2)
{
return Complex (real*c2.real-imag*c2.imag,real*c2.imag+imag*c2.real);
}
bool Complex::operator==(Complex &b)
{
return getReal()==b.getReal()&&getImag()==b.getImag();
}
double Complex::getImag(void) const
{
return imag;
}
double Complex::getReal(void) const
{
return real;
}
double Complex::setReal(double real)
{
return this->real=real;
}
double Complex::setImag(double imag)
{
return this->imag=imag;
}
int main(void)
{
Complex a(4,5),b(6,7),c(10,12);
std::cout<<"a: "<<a.getReal()<<"+"<<a.getImag()<<"i"<<std::endl;
std::cout<<"b: "<<b.getReal()<<"+"<<b.getImag()<<"i"<<std::endl;
std::cout<<"c: "<<c.getReal()<<"+"<<c.getImag()<<"i"<<std::endl;
std::cout<<"a==b "<<(a==b?"True":"False")<<std::endl;
std::cout<<"a+b==c "<<(a+b==c?"True":"False")<<std::endl;
return 0;
}