c++中运算符重载,+,-,--,+=,-=,*,/,*=,/=,




#include<iostream>
#include<stdlib.h>
using namespace std; 
class Complex
{
public:
    Complex(float r=0,float i =0):_r(r),_i(i)
	{
	}
	void print() const
	{
		cout<<" _r "<<_r<<" _i "<<_i<<endl;
	}
private:
	float _r;
	float _i;
public:
	const Complex& operator+=(const Complex & y);
	const Complex& operator-=(const Complex & y);
	const Complex& operator*=(const Complex & y);
	const Complex& operator/=(const Complex & y);
	const Complex operator-(const Complex & y);
	const Complex operator+(const Complex & y);
	const Complex Complex::operator--();
	const bool operator==(const Complex & y);
	const bool operator!=(const Complex & y);
};
inline const Complex Complex::operator-(const Complex & y)
{
	Complex c;
	c._r=_r-y._r;
	c._i=_i-y._i;
	return c;
}
inline const Complex Complex::operator--()
{
	_r=_r-1;
	_i=_i-1;
	return *this;
}
inline const bool Complex::operator==(const Complex & y)
{
	bool b=true;
	if((*this)._r!=y._r||(*this)._i!=y._i)
		b=false;
	
	return b;
}
inline const bool Complex::operator!=(const Complex & y)
{
	bool b=true;
	if((*this)._r==y._r&&(*this)._i==y._i)
		b=false;
	
	return b;

}
inline const Complex Complex::operator+(const Complex & y)
{
	Complex c;
	c._r=_r+y._r;
	c._i=_i+y._i;
	return c;
}
inline const Complex& Complex::operator+=(const Complex & y)
{
	_r=_r+y._r;
	_i=_i+y._i;
	return *this;
}
inline const Complex& Complex::operator-=(const Complex & y)
{
	*this=*this-y;
    return *this;
}
inline const Complex& Complex::operator*=(const Complex & y)
{
	_r=_r*y._r-_i*y._i;
	_i=_r*y._i+_i*y._r;
	return *this;
}
inline const Complex& Complex::operator/=(const Complex & y)
{
	if(y._r==0 && y._i==0)
	{
		exit(1);
	}
	float den=_r*y._r+_i*y._i;
	_r=(_r*y._r+_i*y._i)/den;
	_i=(_i*y._r-_r*y._i)/den;
    return *this;
}
int main()
{
	Complex x(2,3),y(-1,3);
	cout<<" x is ";
	x.print();
	cout<<" y is ";
	y.print();
	
	(x+=y).print();
	x.operator+=(y).print();
	(x-=y).print();
	x.operator-=(y).print();
	(x*=y).print();
	x.operator*=(y).print();
	(x/=y).print();
	x.operator/=(y).print();
	
	cout<<(x==y)<<endl;
		cout<<(x!=y)<<endl;
	return 0;
	
}


posted @ 2013-08-06 19:19  shouqiang Wei  阅读(385)  评论(0编辑  收藏  举报