求教高手,complex模板如何转成用声明对象的做法
程序如下:
HPP
#include<iostream.h>
#include <cmath>
// class
class complex
{
private:
double a,b;
double _copy;
public:
double getreal();
double getimag();
double getZ();
complex(int x)
{
a=x;b=0;
}
complex(double av,double bv):a(av),b(bv)
{
}
complex(){}
complex(complex& _copy)
{
a=_copy.a;
b=_copy.b;
}
friend ostream& operator<<(ostream& i,complex& j);
friend istream& operator>>(istream& g,complex& i);
friend complex operator+(complex& x,complex& y);
friend complex operator-(complex& x,complex& y);
friend complex operator*(complex& x,complex& y);
friend complex operator/(complex& x,complex& y);
complex operator=(complex& y);
void output()
{
cout<<"z="<<sqrt((a*a)+(b*b))<<endl;
}
void put()
{
cout<<"("<<a<<"+"<<b<<"i"<<")"<<endl;
}
void gen()
{int sign=1, double g,h;
if(b<0)
sign=-1;
else
sign=1;
g=sqrt((sqrt((a*a)+(b*b))+a)/2);
h=sign*sqrt((sqrt((a*a)+(b*b))-a)/2);
cout<<"the sqrt-root is: "<<g<<"+"<<h<<"i"<<endl;
}
};
ostream& operator<<(ostream& stream ,complex& x)
{
x.put();
return stream;
}
//input
istream& operator>>(istream& stream,complex& x)
{
cout<<"\treal=";
cin>>x.a;
cout<<"\timag=";
cin>>x.b;
return stream;
}
//add
complex operator+(complex& x,complex& y)
{
return complex(x.a+y.a,x.b+y.b);
}
//sub
complex operator-(complex& x,complex& y)
{
return complex(x.a-y.a,x.b-y.b);
}
//mul
complex operator*(complex& x,complex &y)
{
return complex((x.a*y.a)-(x.b*y.b),(x.a*y.b)+(x.b*y.a));
}
//div
complex operator/(complex& x,complex& y)
{
return complex(((x.a*y.a+x.b*y.b))/(y.a*y.a+y.b*y.b),(x.b*y.a-x.a*y.b)/(y.a*y.a+y.b*y.b));
}
//assignment
complex complex::operator=(complex& y)
{
this->a=y.a;
this->b=y.b;
return *this;
}
double complex::getreal()
{
return a;
}
double complex::getimag()
{
return b;
}
double complex::getZ()
{
return sqrt(a*a+b*b);
}
CPP
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
int main(void)
{
double a ,b ,c ;
cout<<"input a b c:";
cin>>a>>b>>c;
complex<double> x1,x2;
double d = b * b - 4.0 * a * c;
if (d >= 0)
{
x1 = (-b + sqrt(d))/(2*a);
x2 = (-b - sqrt(d))/(2*a);
}
else
{
x1 = complex<double>((-b)/(2*a), sqrt(-d)/(2*a));
x2 = complex<double>((-b)/(2*a), -(sqrt(-d)/(2*a)));
}
cout << "x1 = " << x1.real() << " + " << x1.imag() << "i" << endl;
cout << "x2 = " << x2.real() << " + " << x2.imag() << "i" << endl;
return 0;
}
请高手帮我改一下