复数类,运算符重载(赋值运算符等)
合集下载
相关主题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
*/
#include<iostream.h>
class Complex
{
private :
double real;
double imag;
public:
Complex(double r=0,double i=0)
{
real=r;
imag=i;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
Complex(Complex &c)
{
real=c.real ;
imag=c.imag ;
}
Complex operator +(double x)
{
Complex temp;
temp.real = real+x;
temp.imag = imag;
return temp;
}
Complex operator +(Complex &c)
/*定义复数类Complex,
(1)定义私有数据成员,实部和虚部;
(2)定义带默认值的构造函数,给数据成员赋值,默认值为0;
(3)定义输出函数void display(),输出格式如“3+4i”或“-3-4i”;
(4)定义复数与复数的加、减运算符重载;复数加实数运算符重载;赋值运算符重载;
(5)定义主函数,对上述成员函数进行测试。
b=4+5i
c=a=2+3i
f=a+b=6+8i
d=a+4=6+3i
g=a-b=2+2i
Press any key to continue
{
Complex temp;
temp.real =c.real +real;
temp.imag =c.imag +imag;
return temp;
}
Complex operator =(Complex & c)
{
real=c.real ;
imag=c.imag ;
return *this;
}
Complex operator -(Complex &百度文库c)
b.display();
c=a;
cout<<"c=a=";
c.display ();
f=a+b;
cout<<"f=a+b=";
f.display();
d=a+4;
cout<<"d=a+4=";
d.display ();
g=a-b;
cout<<"g=a-b=";
g.display();
}
结果:
a=2+3i
{
Complex temp;
temp.real =c.real -real;
temp.imag =c.imag -imag;
return temp;
}
};
void main()
{
Complex a(2,3),b(4,5),c,d,f,g;
cout<<"a=";
a.display();
cout<<"b=";
#include<iostream.h>
class Complex
{
private :
double real;
double imag;
public:
Complex(double r=0,double i=0)
{
real=r;
imag=i;
}
void display()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
Complex(Complex &c)
{
real=c.real ;
imag=c.imag ;
}
Complex operator +(double x)
{
Complex temp;
temp.real = real+x;
temp.imag = imag;
return temp;
}
Complex operator +(Complex &c)
/*定义复数类Complex,
(1)定义私有数据成员,实部和虚部;
(2)定义带默认值的构造函数,给数据成员赋值,默认值为0;
(3)定义输出函数void display(),输出格式如“3+4i”或“-3-4i”;
(4)定义复数与复数的加、减运算符重载;复数加实数运算符重载;赋值运算符重载;
(5)定义主函数,对上述成员函数进行测试。
b=4+5i
c=a=2+3i
f=a+b=6+8i
d=a+4=6+3i
g=a-b=2+2i
Press any key to continue
{
Complex temp;
temp.real =c.real +real;
temp.imag =c.imag +imag;
return temp;
}
Complex operator =(Complex & c)
{
real=c.real ;
imag=c.imag ;
return *this;
}
Complex operator -(Complex &百度文库c)
b.display();
c=a;
cout<<"c=a=";
c.display ();
f=a+b;
cout<<"f=a+b=";
f.display();
d=a+4;
cout<<"d=a+4=";
d.display ();
g=a-b;
cout<<"g=a-b=";
g.display();
}
结果:
a=2+3i
{
Complex temp;
temp.real =c.real -real;
temp.imag =c.imag -imag;
return temp;
}
};
void main()
{
Complex a(2,3),b(4,5),c,d,f,g;
cout<<"a=";
a.display();
cout<<"b=";