用C++语言实现一个复数类,包括复数加、减、乘、除、加等、减等、乘等及除等8个运算符的重载。
#include <iostream>
using namespace std;
class Complex//复数类
{
friend ostream& operator<<(ostream& _cout, const Complex& c);//重载<<操作符
public:
Complex(const double real = 0.0, const double image = 0.0);//构造函数
Complex(const Complex& c);//拷贝构造函数
~Complex();//析构函数
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);
Complex& operator+=(const Complex& c);
Complex& operator-=(const Complex& c);
Complex& operator*=(const Complex& c);
Complex& operator/=(const Complex& c);
private:
double _real;//复数实部
double _image;//复数虚部
};
//类外实现成员函数
Complex::Complex(const double real, const double image)//构造函数
{
_real = real;
_image = image;
}
Complex::~Complex()//析构函数
{}
Complex::Complex(const Complex& c)//拷贝构造函数
{
_real = c._real;
_image = c._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 temp(_real + c._real, _image + c._image);
return temp;
}
Complex Complex::operator-(const Complex& c)//重载-
{
Complex temp(_real - c._real, _image - c._image);
return temp;
}
Complex Complex::operator*(const Complex& c)//重载*
{
Complex temp(_real*c._real - _image*c._image, _real*c._image + _image*c._real);
return temp;
}
Complex Complex::operator/(const Complex& c)//重载/
{
double ret = c._real*c._real + c._image*c._image;
Complex temp((_real*c._real + _image*c._image) / ret, (_image*c._real - _real*c._image) / ret);
return temp;
}
Complex& Complex::operator+=(const Complex& c)//重载+=
{
_real += c._real;
_image += c._image;
return *this;
}
Complex& Complex::operator-=(const Complex& c)//重载-=
{
_real -= c._real;
_image -= c._image;
return *this;
}
Complex& Complex::operator*=(const Complex& c)//重载*=
{
_real = _real*c._real - _image*c._image;
_image = _real*c._image + _image*c._real;
return *this;
}
Complex& Complex::operator/=(const Complex& c)//重载/=
{
double tmp = 0.0;
double ret = c._real*c._real + c._image*c._image;
tmp = (_real*c._real + _image*c._image) / ret;
_image = (_image*c._real - _real*c._image) / ret;
_real = tmp;
return *this;
}
ostream& operator<<(ostream& _cout, const Complex& c)//重载<<操作符,使复数的打印形式为 a+bi
{
_cout << c._real << "+" << c._image << "i";
return _cout;
}
int main()
{
//对部分功能的测试
Complex a(1.0, 2.0);
Complex b(3.0, 4.0);
Complex c;
Complex d(a);
c = a / b;
cout << c << endl;
return 0;
}