C++问题 急求

2024-12-16 22:22:50
推荐回答(1个)
回答1:

友元形式;
class Complex
{
public:
Complex(double r=0,double i=0);
void print();
friend Complex operator+(Comple &a,Compkex &b);
friend Complex operator-(Complex &a,Complex &b);
frined Complex operator*(Complex &a,Complex &b);
frined Complex operator/(Complex &a,Complex &b);
private:
double real;
double imag;
};
Complex operator+(Complex &a,Complex &b) //定义运算符+重载函数
{ Complex temp;
temp.real=a.real+b.real;
temp.imag=a.imag+b.imag;
return temp;
}
//定义运算符-重载函数和+相似,不重复了!
Complex operator*(Complex &a,Complex &b)
{Complex temp;
temp.real=a.real*b.real-a.imag*b.imag;
temp.imag=a.real*b.imag+a.imag*b.real;
return temp;
}
Complex operator(Complex &a,Complex &b)
{ Complex temp;
double t;
t=1/(b.real*b.real+b.imag*b.imag);
temp.real=(a.real*b.real+a.imag*b.imag)*t;
temp.imag=(b.real*a.imag-a.real*b.imag)*t;
return temp;
}
成员函数形式:
class Complex
{
public:
Coimplex(double r=0.0,double i=0.0);
void print(0;
Complex operator+(Complex c);
Complex operator-(Complex c);
Complex operator*(Complex c);
Complex operator/(Complex c);
private:
double real;
double imag;
};
Complex Complex::operator-(Complex c)
{
Complex temp;
temp.real=real-c.real;
temp.imag=imag-c.imag;
return temp;
}
Complex Complex::operator*(Complex c)
{ Complex temp;
temp.real=real*c.real-imag*c.imag;
temp.imag=real*c.imag+imag*c.real;
return temp;
}
Complex Complex::operator/(Complex c)
{ Complex temp;
double t;
t=1/(c.real*c.real+c.imag*c.imag);
temp.real=(real*c.real+imag*c.imag)*t;
temp.imag=(c.real*imag-rael*c.imag)*t;
return temp;
}