天天看點

c++運算符重載(C++實作複數運算)

class Complex//複數類,重載運算符使其能進行複數運算
{
private:
	double x;
	double y;
public:
	double GetValuex(){return x;};
	double GetValuey(){return y;};
	void SetValue(double m0,double n0){x=m0;y=n0;};
public:
	Complex operator +(Complex m);
	Complex operator -(Complex m);
	Complex operator *(Complex m);
	Complex operator /(Complex m);
};
Complex Complex::operator +(Complex m)//重載 + 
{
	Complex n;
	n.x=x + m.x;
	n.y=y + m.y;
	return n;
}
Complex Complex::operator -(Complex m)//重載 - 
{
	Complex n;
	n.x=x - m.x;
	n.y=y - m.y;
	return n;
}
Complex Complex::operator *(Complex m)//重載 *
{
	Complex n;
	n.x=x*m.x+y*m.y;
	n.y=x*m.y+y*m.x;
	return n;
}
Complex Complex::operator /(Complex m)//重載 /
{
	Complex n;
	n.x=(x*m.x-y*m.y)/(m.x*m.x+m.y*m.y);
	n.y=(y*m.x-x*m.y)/(m.x*m.x+m.y*m.y);
	return n;
}

#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
	Complex a,b,c;
	a.SetValue(1,1);
	b.SetValue(2,2);
	c=a*b;
	cout<<c.GetValuex();
	cout<<c.GetValuey();
	return 0;
}
           

繼續閱讀