运算符重载的实现代码

来源:互联网 发布:环太平洋配乐 知乎 编辑:程序博客网 时间:2024/06/10 11:56
# include <iostream>
using namespace std;
class Complex
{
friend ostream& operator<<(ostream& _cout, const Complex &c1);
public:
Complex(const double real, const double image)


:_real(real)
, _image(image)


{}
Complex(const Complex & complex)
{
_real = complex._real;
_image = complex._image;
}
Complex operator+(const Complex&c)
{
Complex C(0.0, 0.0);
C._real = _real + c._real;
C._image = _image + c._image;
return C;
}
Complex operator-(const Complex&c)
{
Complex C(0.0, 0.0);
C._real = _real - c._real;
C._image = _image - c._image;
return C;
}
Complex operator*(const Complex&c)
{
Complex C(0.0, 0.0);
C._real = _real * c._real;
C._image = _image * c._image;
return C;
}
Complex operator/(const Complex&c)
{
Complex C(0.0, 0.0);
C._real = _real / c._real;
C._image = _image / c._image;
return C;
}
Complex& operator+=(const Complex&c)
{

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


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


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


_real = _real / c._real;
_image = _image / c._image;
return *this;
}
Complex operator&(const Complex &c)
{
Complex C(0.0, 0.0);
C._real=(int)_real & (int)(c._real);
C._image=(int)_image & (int)(c._image);
return C;
}
bool operator>(const Complex&c)
{
if(_real > c._real)
return 1;
else
return 0;
}
bool operator<(const Complex&c)
{
return _real < c._real ? 1 : 0;
}
bool operator==(const Complex&c)
{
return _real == c._real ? 1 : 0;
}
bool operator!=(const Complex&c)
{
return _real != c._real ? 1 : 0;
}





private:
double _real;
double _image;

};
 ostream& operator<<(ostream& _cout, const Complex &c1)
{
_cout <<"("<<c1. _real <<","<< c1. _image<<")";
return _cout;


}
int main()
{
Complex c1(2.0, 3.0);
cout << c1 << endl; 
Complex c2(c1);
cout << c2 << endl;
cout<<c1.operator+(c2)<<endl;
cout << c1.operator-(c2) << endl;
cout << c1.operator*(c2) << endl;
cout << c1.operator/(c2) << endl;
cout << c1.operator+=(c2) << endl;
cout << c1 << endl;
cout << c1.operator/=(c2) << endl;
cout << c1.operator-=(c2) << endl;
cout << c1.operator*(c2) << endl;
cout << c1<<c2 << endl;
cout << c1.operator&(c2) << endl;
cout << c1.operator>(c2) << endl;
cout << c1.operator<(c2) << endl;
cout << c1.operator==(c2) << endl;
cout << c1.operator!=(c2) << endl;
system("pause");


return 0;


}
0 0
原创粉丝点击