复数类
- 类的四个成员函数:构造、析构、拷贝构造、赋值运算符重载
- 等于、不等于运算符重载
- +、+=、-、-=、*、*=、/、/=
- 求模
- 打印
- 不提供大小比较(无法区分复数相等和模相等)
comple.h
#ifndef __COMPLEX_H__
#define __COMPLEX_H__
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double real = 0.0, double image = 0.0)
:_real(real),
_image(image)
{}
~Complex()
{
cout << "~Complex" << endl;
}
Complex(Complex& c)
:_real(c._real)
, _image(c._image)
{}
Complex& operator=(Complex& c)
{
if (this != &c)
{
_real = c._real;
_image = c._image;
}
return *this;
}
bool operator==(const Complex& c)
{
if (_real == c._real && _image == c._image)
return true;
return false;
}
bool operator!=(const Complex& c)
{
if (_real != c._real || _image != c._image)
return true;
return false;
}
Complex& operator++()
{
_real++;
_image++;
return *this;
}
Complex operator++(int)
{
Complex ret = *this;
_real++, _image++;
return ret;
}
Complex& operator--()
{
_real--;
_image--;
return *this;
}
Complex operator--(int)
{
Complex ret = *this;
_real--, _image--;
return ret;
}
Complex operator+(Complex& c)const
{
Complex ret(c);
ret._real += _real;
ret._image += _image;
return ret;
}
Complex& operator+=(const Complex& c)
{
_real += c._real;
_image += c._image;
return *this;
}
Complex operator-(Complex& c)const
{
Complex ret;
ret._real = _real - c._real;
ret._image = _image - c._image;
return ret;
}
Complex& operator-=(const Complex& c)
{
_real -= c._real;
_image -= c._image;
return *this;
}
Complex operator*(const Complex& c)const
{
Complex ret;
ret._real = _real*c._real - _image*c._image;
ret._image = _image*c._real + _real*c._image;
return ret;
}
Complex& operator*=(const Complex& c)
{
*this = (*this)*c;
return *this;
}
Complex operator/(const Complex&c)const
{
Complex ret;
ret._real = (_real*c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
ret._image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return ret;
}
Complex& operator/=(const Complex&c)
{
*this = (*this) / c;
return *this;
}
double abs()
{
return sqrt(_real*_real + _image*_image);
}
void display()const
{
cout << "(" << _real << " + " << _image << "i" << ")" << endl;
}
private:
double _real;
double _image;
};
#endif
测试函数
text1()
void text1()
{
Complex com1;
com1.display();
Complex com2(3, 5);
com2.display();
com1 = com2;
com1.display();
cout << (com1 == com2) << endl;
cout << (com1 != com2) << endl;
cout << com1.abs() << endl;
com1++.display();
(++com1).display();
cout << (com1 == com2) << endl;
cout << (com1 != com2) << endl;
com2--.display();
(--com2).display();
}

text2()
void text2()
{
Complex com1(4, 4);
Complex com2(2, 2);
Complex com3 = com1 + com2;
com3.display();
com3 += com2;
com3.display();
com3 -= com2;
com3.display();
com3 *= com2;
com3.display();
com3 /= com2;
com3.display();
}
