定义一个复数类Complex,重载运算符“+”,“-”,“*”,“/”,使之能用于复数的加、减、乘、除.运算符重载作为Complex的类的成员函数,编程序,求两个复数的和,差,积,商.程序:#include using namespace std;class Complex //定义complex类{public:Complex(){real=0;imag=0;} //定义构造函数Complex(double r,double i){real=r;imag=i;} //构造函数重载Complex operator+(Complex &c2); //声明复数相加的函数Complex operator-(Complex &c2); //声明复数相减的函数Complex operator*(Complex &c2); //声明复数相乘的函数Complex operator/(Complex &c2); //声明复数相除的函数void display();private:double real; //实部

问题描述:

定义一个复数类Complex,重载运算符“+”,“-”,“*”,“/”,使之能用于复数的加、减、乘、除.
运算符重载作为Complex的类的成员函数,编程序,求两个复数的和,差,积,商.
程序:
#include
using namespace std;
class Complex //定义complex类
{public:
Complex(){real=0;imag=0;} //定义构造函数
Complex(double r,double i){real=r;imag=i;} //构造函数重载
Complex operator+(Complex &c2); //声明复数相加的函数
Complex operator-(Complex &c2); //声明复数相减的函数
Complex operator*(Complex &c2); //声明复数相乘的函数
Complex operator/(Complex &c2); //声明复数相除的函数
void display();
private:
double real; //实部
double imag; //虚部
};
Complex Complex::operator+(Complex &c2) //定义复数相加的函数
{Complex c;
c.real=real+c2.real; //实部相加
c.imag=imag+c2.imag; //虚部相加
return c;}
Complex Complex::operator-(Complex &c2) //定义复数相减的函数
{Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;}
Complex Complex::operator*(Complex &c2) //定义复数相乘的函数
{Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;}
Complex Complex::operator/(Complex &c2) //定义复数相除的函数
{Complex c;
c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;}
void Complex::display() //定义输出函数
{cout

#include
using namespace std;
class Complex //定义complex类
{public:
Complex(){real=0;imag=0;} //定义构造函数
Complex(double r,double i){real=r;imag=i;} //构造函数重载
friend Complex operator+(Complex &c1,Complex &c2); //声明复数相加的函数
friend Complex operator-(Complex &c1,Complex &c2); //声明复数相减的函数
friend Complex operator*(Complex &c1,Complex &c2); //声明复数相乘的函数
friend Complex operator/(Complex &c1,Complex &c2); //声明复数相除的函数
void display();
private:
double real; //实部
double imag; //虚部
};
Complex operator+(Complex &c1,Complex &c2) //定义复数相加的函数
{Complex c;
c.real=c1.real+c2.real; //实部相加
c.imag=c1.imag+c2.imag; //虚部相加
return c;}
Complex operator-(Complex &c1,Complex &c2) //定义复数相减的函数
{Complex c;
c.real=c1.real-c2.real;
c.imag=c2.imag-c2.imag;
return c;}
Complex operator*(Complex &c1,Complex &c2) //定义复数相乘的函数
{Complex c;
c.real=c1.real*c2.real-c1.imag*c2.imag;
c.imag=c1.imag*c2.real+c1.real*c2.imag;
return c;}
Complex operator/(Complex &c1,Complex &c2) //定义复数相除的函数
{Complex c;
c.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;}
void Complex::display() //定义输出函数
{cout