您的位置:首页 > 其它

通过运算符重载实现复数运算

2015-08-19 16:26 232 查看
#include<iostream>
using namespace std;
class Complex
{
public:
// 带缺省值的构造函数
Complex(double real = 0, double image = 0)
{
cout << "带缺省值的构造函数" << endl;
_real = real;
_image = image;
}
// 析构函数
~Complex()
{
cout << "析构函数" << endl;
}
// 拷贝构造函数
Complex(const Complex& d)
{
cout << "拷贝构造函数" << endl;
_real = d._real;
_image = d._image;
}
// 赋值运算符重载
Complex& operator= (const Complex& d)
{
cout << "赋值运算符重载" << endl;
if (&d != this)
{
_real = d._real;
_image = d._image;
}

return *this;
}
void Display()
{
cout << "real = " << _real << "  " << "image = " << _image << endl;
}

public:
Complex& operator++()//前置++
{
_real++;
return *this;
}
Complex operator++(int)//后置++ int为标示符区分前置++和后置++
{
Complex tmp(*this);
_real++;
return tmp;
}

Complex& operator--()//前置--
{
_real--;
return *this;
}
Complex operator--(int)//后置--
{
Complex tmp(*this);
_real--;
return tmp;
}

Complex operator+(const Complex& c)
{
Complex tmp;
tmp._real = _real + c._real;
tmp._image = _image + c._image;
return tmp;
}
Complex operator-(const Complex& c)
{
Complex tmp;
tmp._real = this->_real - c._real;
tmp._image = this->_image - c._image;
return tmp;
}

Complex& operator-=(const Complex& c)
{
_real -= c._real;
_image -= c._image;
return *this;
}
Complex& operator+=(const Complex& c)
{
_real += c._real;
_image += c._image;
return *this;
}

Complex operator*(const Complex& c)
{
Complex tmp;
tmp._real = (_real * c._real) - (_image * c._image);
tmp._image = (_real * c._image) + (_image * c._real);
return tmp;
}
Complex operator/(const Complex& c)
{
Complex tmp;
double t = (c._real * c._real) + (c._image * c._image);
tmp._real = (_real * c._real - _image * c._image) / t;
tmp._image = (_real * c._image + _image * c._real) / t;
return tmp;
}

private:
double _real;       // 实部
double _image;      // 虚部
};
void TestMultiply()
{
Complex c1(3.3, 1.1), c2(1.1, 2.2);
Complex c3;
c3 = c1 * c2; //(1.21,8.47)
c3.Display();
}
void TestDivide()
{
Complex c1(3.3, 1.1), c2(1.1, 2.2);
Complex c3;
c3 = c1 / c2; //(0.2,1.4)
c3.Display();
}
void TestAdd_Reduce()
{
Complex c1(4.3, 2.1), c2(1.5, 6.5), c3;
c3 = c2 + c1;
c3.Display();//(5.8,8.6)
c3 = c2 - c1;//(2.2,1.1)
c3.Display();
}

int main()
{
Complex c1(2.2, 1.1);
Complex c2(c1);//代入法拷贝构造
c1.Display();
c2.Display();
Complex c3 = c1;//赋值法拷贝构造
c3.Display();
Complex c4(3.3, 1.1);
c1 = c4;//赋值运算符重载
c1.Display();

++c4;//(4.3,1.1)
c4.Display();
--c4;//(3.3,1.1)
c4.Display();
c3 = c4++;
c3.Display();//(3.3,1.1)
c4.Display();//(4.3,1.1)
c4 -= c1;// (1,0)
c4.Display();
c4 += c1;//(4.3,1.1)
c4.Display();

TestAdd_Reduce();
TestMultiply();
TestDivide();
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: