#include<iostream>
using namespace std;
class Complex
{
public:
friend ostream& operator<<(ostream& _cout, Complex c); //输出函数需要访问私有成员,声明为友元函数
Complex(double real = 0.0, double image = 0.0);
Complex(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);
Complex& operator/=(const Complex& c);
~Complex();
private:
double _real;
double _image;
};
Complex::Complex(double real, double image):// 构造函数
_real(real),
_image(image)
{
}
Complex::Complex(const Complex& c) :// 拷贝构造
_real(c._real)
, _image(c._image)
{
}
Complex& Complex::operator=(const Complex &c) // 赋值运算符重载 返回值为引用
{
if (this != &c)
{
this->_real = c._real;
this->_image = c._image;
}
return *this;
}
Complex Complex::operator+(const Complex &c)// 复数相加 +运算符重载
{
Complex temp;
temp._real = this->_real + c._real;
temp._image = this->_image + c._image;
return temp;
}
Complex Complex::operator-(const Complex &c)// 复数相减 -运算符重载
{
Complex temp;
temp._real = this->_real - c._real;
temp._image = this->_image - c._image;
return temp;
}
Complex Complex::operator*(const Complex &c)// 复数相乘 *运算符重载
{
Complex temp;
temp._real = this->_real*c._real - this->_image*c._image;
temp._image = this->_real*c._image + c._real*this->_image;
return temp;
}
Complex Complex::operator/(const Complex &c)// 复数相除 /运算符重载
{
Complex temp;
temp._real = (this->_real * c._real + this->_image*c._image) / (c._real*c._real + c._image *c._image);
temp._image = (c._real * this->_image - this->_real*c._image) / (c._real*c._real + c._image *c._image);
return temp;
}
Complex& Complex:: operator+=(const Complex &c)// 复数+=运算符重载
{
this->_real = this->_real + c._real;
this->_image = this->_image + c._image;
return *this;
}
Complex& Complex:: operator-=(const Complex &c)//// 复数-=运算符重载
{
this->_real = this->_real - c._real;
this->_image = this->_image - c._image;
return *this;
}
Complex& Complex::operator*=(const Complex& c)// 复数 *=运算符重载
{
this->_real = this->_real*c._real - this->_image*c._image;
this->_image = this->_real*c._image + c._real*this->_image;
return *this;
}
Complex& Complex::operator/=(const Complex& c)// 复数 /=运算符重载
{
this->_real = (this->_real * c._real + this->_image*c._image) / (c._real*c._real + c._image *c._image);
this->_image = (c._real * this->_image - this->_real*c._image) / (c._real*c._real + c._image *c._image);
return *this;
}
Complex::~Complex()// 析构函数
{
}
ostream& operator<<(ostream& _cout, Complex c)// 输出运算符<<重载
{
_cout << c._real << " " << c._image;
return _cout;
}
int main()
{
Complex a(2, 0);
Complex b(a);
a *= b;
cout << a << endl;
system("pause");
return 0;
}
复数类 运算符重载
最新推荐文章于 2021-03-17 15:58:41 发布