#include<iostream>
using namespace std;
class Complex
{
public:
void Display()
{
cout<<"Real:"<<_real<<"Image:"<<_image<<endl;
}
// 带缺省值的构造函数
Complex (double real = 0.0, double image = 0.0)
:_real(real)
,_image(image)
{
//初始化列表
cout<<"Complex (double real = 0.0, double image = 0.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;
}
Complex operator +(Complex& c) //声明成员函数重载运算符"+"
{
cout<<"operator +(Complex& c)"<<endl;
Complex temp;
temp._real = this->_real + c._real;
temp._image = this->_image + c._image;
return temp;
}
Complex operator -(Complex& c)
{
cout<<"operator -(Complex& c)"<<endl;
Complex temp;
temp._real = this->_real - c._real;
temp._image = this->_image - c._image;
return temp;
}
Complex operator *(Complex& c)
{
cout<<"operator *(Complex& c)"<<endl;
Complex temp;
temp._real = this->_real*c._real - this->_image * c._image;
temp._image = this->_real *c._image + this->_image * c._real;
return temp;
}
Complex operator /(Complex& c)
{
cout<<"operator -(Complex& c)"<<endl;
Complex temp;
temp._real = (this->_real*c._real + this->_image * c._image)/
(c._real*c._real + c._image * c._image);
temp._image = (this->_image * c._real -this->_real *c._image)/
(c._real*c._real + c._image * c._image);
return temp;
}
Complex& operator++() //前置++
{
this->_real++;
return *this;
}
Complex operator++(int) //后置++
{
Complex temp(*this);
this->_real++;
return temp;
}
Complex& operator--() //前置--
{
this->_real--;
return *this;
}
Complex operator--(int) //后置--
{
Complex temp(*this);
this->_real--;
return temp;
}
Complex& operator-=(const Complex& c)
{
this->_real -= c._real;
this->_image -= c._image;
return *this;
}
Complex& operator+=(const Complex& c)
{
this->_real += c._real; //(this->_real = this->_real + c._real)
this->_image += c._image;
return *this;
}
private:
double _real;
double _image;
};
void TestComplex ()
{
Complex c1(2.2, 1.1);
Complex c2 = c1++;
c1.Display();
c2.Display();
}
int main()
{
Complex c1(2.2,1.1);
c1.Display ();
Complex c2(c1); //调用拷贝构造函数
c2.Display();
Complex c3; //赋值运算符的重载
c3 = c2;
c3.Display();
Complex c4 = c1 + c2;
c4.Display();
Complex c5 = c3 - c2;
c5.Display();
Complex c6 = c3 * c2;
c6.Display();
Complex c7(c1);
c7++;
c7.Display();
Complex c8;
c8 += c1;
c8.Display();
getchar();
return 0;
}
【C++】复数类
最新推荐文章于 2022-07-27 08:25:08 发布