<span style="font-size:18px;">#include<iostream>
using namespace std;
class Complex
{
private:
double _real;
double _image ;
public:
Complex(double a=0.0,double b=0.0)
{
cout<<"constructing"<<endl;
_real=a;
_image=b;
}
~ Complex()
{
cout<<"destructing"<<endl;
}
Complex(const Complex &p)
{
cout<<"copy constructing"<<endl;
_real=p._real;
_image=p._image;
}
void display()
{
cout<<_real;
if(_image>0)cout<<"+";
if(_image!=0)cout<<_image<<"i"<<endl;
}
Complex& operator++();
Complex operator++(int);
Complex& operator--();
Complex operator--(int); //后置--
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 Complex::operator +(const Complex& c)
{
Complex tmp;
tmp._real=_real+c._real;
tmp._image=_image+c._image;
return tmp;
}
Complex Complex::operator -(const Complex& c)
{
Complex tmp;
tmp._real=_real-c._real;
tmp._image=_image-c._image;
return tmp;
}
Complex 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 Complex::operator /(const Complex &c)
{
Complex tmp;
double t;
t=1/(c._real*c._real+c._image*c._image);
tmp._real=(_real*c._real+_image+c._image)*t;
tmp._image=(_image*c._real+_real+c._image)*t;
return tmp;
}
Complex& Complex::operator++()
{
this->_real++;
this->_image++;
return *this;
/*Complex tmp;
tmp._real=_real++;
tmp._image=_image++;
return tmp;//去掉引用*/
}
Complex& Complex::operator --()
{
this->_real--;
this->_image--;
return *this;
}
Complex& Complex::operator+=(const Complex& c)
{
//Complex tmp;
_real=this->_real+c._real;
_image=this->_image+c._image;
return *this;
}
Complex& Complex::operator-=(const Complex& c)
{
_real=this->_real-c._real;
_image=this->_image-c._image;
return *this;
}
Complex Complex ::operator++(int)
{
Complex tmp(*this);
this->_image++;
this->_real++;
return tmp;
}
Complex Complex ::operator--(int)
{
Complex tmp(*this);
this->_image--;
this->_real--;
return tmp;
}
int main()
{
Complex A(3,3);
Complex B(A);
Complex C;
Complex D;
D=A*B;
C=A-B;
++C;
C.display();
B.display();
D.display();
return 0;
}</span>
c++类的初创建(复数类)
最新推荐文章于 2022-03-22 10:52:52 发布