复数类的运算符重载
运算符重载指对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
对于复数类,有实部和虚部两部分,因此我们对于+,-,*,/,要列式计算。
如要加上+=,-+,*=,/=也会很容易。
程序如下:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double real = 0.0, double image = 0.0); //声明构造函数时指定默认参数
Complex& operator=(const Complex& c);
Complex operator+(const Complex& c);
Complex operator-(const Complex& c);
Complex operator*(const Complex& c);
Complex operator/(const Complex& c);
void display();
private:
double _real;
double _image;
};
//定义构造函数
Complex::Complex(double real, double image)
{
_real = real;
_image = image;
}
//复数赋值
Complex& Complex::operator=(const Complex& c)
{
if (this != &c)
{
_real = c._real;
_image = c._image;
}
return *this;
}
//复数相加
Complex Complex::operator+(const Complex& c)
{
Complex c1;
c1._real = _real + c._real;
c1._image = _image + c._image;
return c1;
}
//复数相减
Complex Complex::operator-(const Complex& c)
{
Complex c1;
c1._real = _real - c._real;
c1._image = _image - c._image;
return c1;
}
//复数相乘(a+bi)*(c+di)
Complex Complex::operator*(const Complex& c)
{
Complex c1;
c1._real = _real*c._real - _image*c._image;
c1._image = _image*c._real + _real*c._image;
return c1;
}
//复数相除(a+bi)/(c+di)
Complex Complex::operator/(const Complex& c)
{
Complex c1;
c1._real = (_real*c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
c1._image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return c1;
}
void Complex::display()
{
cout << "(" << _real << "," << _image << ")" << endl;
}
void test()
{
Complex c1(1.0, 2.0);
Complex c2(4.0, 5.0);
Complex c3;
c3 = c1.operator+(c2);
c3.display();
c3 = c1.operator-(c2);
c3.display();
c3 = c1.operator*(c2);
c3.display();
c3 = c1.operator/(c2);
c3.display();
c2 = c1.operator=(c1);
c2.display();
}
int main()
{
test();
system("pause");
return 0;
}
在此基础上,就可以直接利用已重载好的运算符来重载+=,-=,*=,/=
程序如下:
//复数加等(a+bi)=(a+bi)+(c+di)
void Complex:: operator+=(const Complex& c)
{
*this=*this+c;
/*_real += c._real;
_image += c._image;*/
}
//复数减等(a+bi)=(a+bi)-(c+di)
void Complex:: operator-=(const Complex& c)
{
*this = *this - c;
/*_real -= c._real;
_image -= c._image;*/
}
//复数乘等(a+bi)=(a+bi)*(c+di)
void Complex:: operator*=(const Complex& c)
{
*this = *this*c;
}
//复数除等(a+bi)=(a+bi)/(c+di)
void Complex::operator/=(const Complex& c)
{
*this = *this / c;
}
void Complex::display()
{
cout << "(" << _real << "," << _image << ")" << endl;
}
void test2()
{
Complex c1(1.0, 2.0);
Complex c2(4.0, 5.0);
c1+=c2;
c1.display();
c1-=(c2);
c1.display();
c1*=(c2);
c1.display();
c1/=(c2);
c1.display();
}
运行结果如下,读者可自行验证。