第六次c++实验

/*
第六次实验:


定义一个复数类Complex,复数有实部虚部,
为其重载+、-、*、/友元;
=、==、!=成员运算符,
为其定义一个Show函数显示复数(格式如:2+i3);
通过main函数验证每个运算符。
*/
#include<iostream.h>
class complex{
private:
double real;
double imag;
public:
complex(double i=0.0,double j=0.0);
void show();
friend complex operator+(complex &a,complex &b);
friend complex operator-(complex &a,complex &b);
friend complex operator*(complex &a,complex &b);
friend complex operator/(complex &a,complex &b);
complex operator=(complex &b);
complex operator==(complex &b);
complex operator!=(complex &b);
};
complex ::complex(double i,double j)
{
real=i;
imag=j;
}
void complex::show ()
{
cout<<real;
if(imag<0)cout<<imag<<"i"<<endl;
if(imag>=0)cout<<"+"<<imag<<"i"<<endl;
}
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 ;
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.imag*b.real+a.real*b.imag;
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 =a.imag*b.real-a.real*b.imag;
return temp;
}
complex complex::operator=(complex &b)
{
real =b.real ;
imag =b.imag ;
cout<<"I am very good!!___每一个都用到赋值语句!!  ";
return 0;
}
complex complex::operator == (complex &b)
{
real==b.real;
imag==b.imag;
cout<<"this equal!..!..!-相等"<<endl; //why ?   can't print out?
return 0;
}
complex complex::operator != (complex &b)
{
real!=b.real;
imag!=b.imag;
cout<<"this is not't equal!!!....!!!!!!!-不相等"<<endl;


/* if(real!=b.real ||imag!=b.imag )
{
cout<<"this is not't equal!!!....!!!!!!!"<<endl; //why can't print!!??
}
*/
return 0;
}
int main()
{
complex a1(2.3,4.6),a2(3.5,6.8),a7(2.3,4.6),a3,a4,a5,a6;
a1.show ();
a2.show ();
a3=a1+a2;
a3.show ();
a4=a1-a2;
a4.show ();
a5=a1*a2;
a5.show ();
a6=a1/a2;
a6.show ();
a1=a2;
a1.show ();
a1==a7;
// a7==a1;
a1!=a2;
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值