标签:复数类
#include<iostream>
using namespace std;
class Complex
{
public:
// 带缺省值的构造函数
Complex(double real = 0, double image = 0)
:_real(real)
, _image(image)
{
cout << "Complex (double real = 0, double image = 0)" << endl;
}
// 析构函数
~Complex()
{
cout << "~Complex()" << endl;
}
// 拷贝构造函数
Complex(const Complex& d)
:_image(d._image)
, _real(d._real)
{
cout << "Complex (const Complex& d)" << endl;
}
// 赋值运算符重载
Complex& operator= (const Complex& d)
{
cout << "operator= (const Complex& d)" << endl;
if (this != &d)
{
this->_real = d._real;
this->_image = d._image;
}
return *this;
}
void Display()
{
cout << "Real:" << _real << "--Image:" << _image << endl;
}
public:
Complex& operator++()
{
this->_real++;
this->_image++;
return *this;
}
Complex operator++(int) //后置++
{
Complex tmp(*this);
this->_real++;
this->_image++;
return tmp;
}
Complex& operator--()
{
this->_real--;
this->_image--;
return *this;
}
Complex operator--(int) //后置--
{
Complex tmp(*this);
this->_real--;
this->_image--;
return tmp;
}
Complex operator+(const Complex& c)
{
return Complex(this->_real + c._real, this->_image + c._image);
}
Complex operator-(const Complex& c)
{
return Complex(this->_real - c._real, this->_image - c._image);
}
Complex operator-=(const Complex& c)
{
return(_real - c._real, _image - c._image);
}
Complex operator+=(const Complex& c)
{
return(_real + c._real, _image + c._image);
}
Complex operator*(const Complex& c)
{
Complex tmp(*this);
this->_real = _real*c._real - _image*c._image;
this->_image = _real*c._image + _image*c._real;
return tmp;
}
Complex operator/(const Complex& c)
{
Complex tmp(*this);
this->_real = (_real*c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
this->_image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return tmp;
}
private:
double _real;
double _image;
};
void Test1()
{
Complex d1(1, 2);
Complex d2(2, 3);
d2 = d1;
d1.Display();
d2.Display();
}
void Test2()
{
Complex d1(1, 2);
Complex d2(2, 3);
d1 = d1 - d2;
d1.Display();
d2.Display();
}
int main()
{
//Test1();
Test2();
return 0;
}
标签:复数类
原文地址:http://10622551.blog.51cto.com/10612551/1696419