复数类的默认成员函数的实现。加减乘除,自增,自减的实现。
#include<iostream>
using namespace std;
class Complex
{
public:
//显示
void Display()
{
cout<<_real<<"+"<<_image<<"i"<<endl;
}
//构造函数
Complex(double x=0.0,double y=0.0)
{
_real=x;
_image=y;
}
//析构函数
~Complex()
{
;//cout<<"析构函数"<<endl;
}
//拷贝构造
Complex(const Complex& c1)
{
if(this!=&c1)
{
_real=c1._real;
_image=c1._image;
}
cout<<"拷贝构造"<<endl;
}
//加法
Complex operator+(Complex &c1)
{
Complex c2;
c2._real=_real+c1._real;
c2._image=_image+c1._image;
return c2;
}
//减法
Complex operator-(Complex &c1)
{
Complex c2;
c2._real=_real-c1._real;
c2._image=_image-c1._image;
return c2;
}
//乘法
Complex operator *(Complex &c1)
{
Complex c2;
c2._real=_real*c1._real;
c2._image=_image*c1._image;
return c2;
}
//除法
Complex operator/(Complex &c1)
{
Complex c2;
c2._real=_real/c1._real;
c2._image=_image/c1._image;
return c2;
}
//加等
Complex& operator+=(const Complex &c1)
{
_real+=c1._real;
_image+=c1._image;
return *this;
}
//减等
Complex& operator-=(const Complex &c1)
{
_real-=c1._real;
_image-=c1._image;
return *this;
}
//前置++
Complex& operator ++()
{
++_real;
++_image;
return *this;
}
//后置++
Complex operator ++(int)
{
Complex tmp(*this);
this->_real++;
this->_image++;
return tmp;
}
//前置--
Complex& operator--()
{
_real--;
_image--;
return *this;
}
//后置--
Complex operator--(int)
{
Complex tmp(*this);
this->_real--;
this->_image--;
return tmp;
}
//判断大小 c1>c2
Complex()
{
;
}
private:
double _real;
double _image;
};
int main()
{
Complex c1(1.0,2.0),c2(2.0,2.0),c3;
cout<<"c1=";
c1.Display();
cout<<"c2=";
c2.Display();
/*c3=c1+c2;
cout<<"c1+c2=";
c3.Display();
c3=c1-c2;
cout<<"c1-c2=";
c3.Display();
c3=c1*c2;
cout<<"c1*c2=";
c3.Display();
c3=c1/c2;
cout<<"c1/c2=";
c3.Display();
c1+=c2;
cout<<"c1=";
c1.Display();
c1-=c2;
cout<<"c1=";
c1.Display();*/
c3=c2+(--c1);
cout<<"c3=";
c3.Display();
cout<<"c1=";
c1.Display();
system("pause");
return 0;
}以写一个复数类,了解C++的三大特性,及默认成员函数的实现。
本文出自 “sunshine225” 博客,请务必保留此出处http://10707460.blog.51cto.com/10697460/1754048
原文:http://10707460.blog.51cto.com/10697460/1754048