提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、题目
二、代码
1
代码如下:
#include<iostream>
using namespace std;
class Complex
{
double Real,Image;
public:
Complex(double r=0,double i=0)
{
Real=r;Image=i;
}
Complex & operator=(Complex &c)
{
Real=c.Real;
Image=c.Image;
return*this;
}
Complex & operator+=(Complex &c)
{
Real=Real+c.Real;
Image=Image+c.Image;
return *this;
}
friend Complex operator+(const Complex &c1,const Complex &c2);
friend Complex operator-(const Complex &ci,const Complex &c2);
void Show()
{
cout<<Real;
if(Image>0) cout<<'+'<<Image<<'i';
else if(Image<0) cout<<Image<<'i';
cout<<endl;
}
};
Complex operator+(const Complex&c1,const Complex&c2)
{
return Complex(c1.Real+c2.Real,c1.Image+c2.Image);
}
Complex operator-(const Complex&c1,const Complex&c2)
{
Complex t;
t.Real=c1.Real-c2.Real;
t.Image=c1.Image-c2.Image;
return t;
}
int main()
{
Complex c1(2,3),c2(4,-2),c3;
c3=c1+c2;
cout<<"c1+c2=";
c3.Show();
c3=c1-c2;
cout<<"c1-c2=";
c3.Show();
c3+=c2;
cout<<"c3+=c2=";
c3.Show();
return 0;
}
2、3
代码如下:
2.#include<iostream>
using namespace std;
int hj(int a,int b)
{
int k=a<b?a:b,i;
for(i=k;i>=1;i--)
if(a%i==0&&b%i==0) return i;
return k;
}
class Fen
{
int a,b;
public:
Fen(int x=1,int y=1)
{
int i=hj(x,y);
a=x/i;
b=y/i;
}
Fen& operator=(Fen&f1)
{
a=f1.a;
b=f1.b;
return *this;
}
Fen operator+(Fen&f1)
{
int x,y;
x=a*(f1.b)+b*(f1.a);
y=b*(f1.b);
return (Fen(x,y));
}
Fen operator-(Fen&f1)
{
int x,y;
x=a*(f1.b)-b*(f1.a);
y=b*(f1.b);
return (Fen(x,y));
}
friend Fen operator*(Fen&f1,Fen&f2);
friend Fen operator/(Fen&f1,Fen&f2);
void show()
{
if(b==0) cout<<"输入有误。"<<endl;
else
{
if(b==1) cout<<a<<endl;
else
{
if(b==-1) cout<<-a<<endl;
else
{
if(a==0) cout<<0<<endl;
else
{
if(a>0&&b>0) cout<<a<<'/'<<b<<endl;
if(a>0&&b<0) cout<<'-'<<a<<'/'<<-b<<endl;
if(a<0&&b>0) cout<<a<<'/'<<b<<endl;
if(a<0&&b<0) cout<<-a<<'/'<<-b<<endl;
}
}
}
}
}
};
Fen operator*(Fen&f1,Fen&f2)
{
return Fen((f1.a)*(f2.a),(f1.b)*(f2.b));
}
Fen operator/(Fen&f1,Fen&f2)
{
return Fen((f1.a)*(f2.b),(f1.b)*(f2.a));
}
int main()
{
Fen f1(4,5),f2(1,2),f4;
f4=f1;
f4.show();
f4=f1+f2;
f4.show();
f4=f1-f2;
f4.show();
f4=f1*f2;
f4.show();
f4=f1/f2;
f4.show();
return 0;
}
3.
#include<iostream>
using namespace std;
class Point
{
int x,y;
public:
Point(int a=0,int b=0)
{
x=a;
y=b;
}
Point operator++()
{
x++;
y++;
return *this;
}
Point operator++(int)
{
Point t=*this;
x++;
y++;
return t;
}
friend Point operator--(Point &m);
friend Point operator--(Point &m,int);
void show()
{
cout<<'('<<x<<','<<y<<')'<<endl;
}
};
Point operator--(Point &m)
{
m.x=m.x-1;
m.y--;
return m;
}
Point operator--(Point &m,int)
{
Point t=m;
m.x--;
m.y--;
return t;
}
int main()
{
Point t(1,1),k(3,3);
t=k--;
t.show();
k.show();
t=--k;
t.show();
k.show();
return 0;
}
总结
如有帮助,还望点赞