SDUTOJ 2677 4-1 复数类的运算符重载

时间:2022-12-25 17:21:34
SDUTOJ 2677 4-1 复数类的运算符重载
#include<iostream>
using namespace std;
class Complex
{
public:
	Complex(){real=0;imag=0;}
	Complex(double r,double i){real=r;imag=i;}
	Complex operator+(Complex &c2);
	Complex operator-(Complex &c3);
	void display();
private:
	double real,imag;
};
Complex Complex::operator +(Complex &c2)
{
	Complex c;
	c.real=real+c2.real;
	c.imag=imag+c2.imag;
	return c;
}
Complex Complex::operator -(Complex &c3)
{
	Complex c5;
	c5.real=real-c3.real;
	c5.imag=imag-c3.imag;
	return c5;
}
void Complex::display()
{   if(imag>0)
	    cout<<real<<"+"<<imag<<"i"<<endl;
    else 
		cout<<real<<imag<<"i"<<endl;
}
int main()
{
	Complex a(3.2,4.5),b(8.9,5.6),c3,c4;
	c3=a+b;
	c4=a-b;
    cout<<"a=";a.display();
	cout<<"b=";b.display();
	cout<<"a+b=";c3.display();
	cout<<"a-b=";c4.display();
	return 0;
}