1、/*1.定义一个复数类,通过重载运算符:+、-、*、/ 等,实现两个复数之间的各种运算。编写一个完整的程序。*/
#include
2、ator * (Complex &,Complex &);
friend Complex operator / (Complex &,Complex &);
void show()
{cout<<"Real="< 3、Complex &a,Complex &b)
{
Complex t;
t.Real=a.Real-b.Real;
t.Image=a.Image-b.Image;
return t;
}
Complex operator * (Complex &a,Complex &b)
{
Complex t;
t.Real=a.Real*b.Real-a.Image*b.Image;
t.Image=a.Real*b.Image+a.Image*a.Real;
return t;
}
Complex operator / (Complex &a,Comp 4、lex &b)
{
Complex t;
t.Real=(a.Real*b.Real+a.Image*b.Image)/(b.Real*b.Real+b.Image*b.Image);
t.Image=(a.Image*a.Real-a.Real*b.Image)/(b.Real*b.Real+b.Image*b.Image);
return t;
}
void main()
{
Complex c1(10,20),c2,c3(50,40);
c2=c1+c3;
c2.show();
c2=c1-c3;
c2.show();
c2=c1*c 5、3;
c2.show();
c2=c1/c3;
c2.show();
}
/*2.定义描述一个三维点,利用友元函数重载"++"和"--"运算符,并区分这两种运算符的前置和后置运算。*/
#include 6、 t.z=z+a.z;
return t;
}
friend point operator ++(point &a);
friend point operator ++(point &,int);
friend point operator --(point &);
friend point operator --(point &,int);
void show()
{cout<<"x="< 7、t;
t.x=++a.x;
t.y=++a.y;
t.z=++a.z;
return t;
}
point operator ++(point &a,int)
{
point t;
t.x=a.x++;
t.y=a.y++;
t.z=a.z++;
return t;
}
point operator --(point &a)
{
point t;
t.x=--a.x;
t.y=--a.y;
t.z=--a.z;
return t;
}
point operator --(point &a,int)
{
poi 8、nt t;
t.x=a.x--;
t.y=a.y--;
t.z=a.z--;
return t;
}
void main()
{
point p1(10,20),p2(30,40),p3;
p3=p3+p1;
p3.show();
p3=++p1;
p3.show();
p1.show();
p3=--p1;
p3.show();
p1.show();
p3=p2++;
p3.show();
p2.show();
p3=p2--;
p3.show();
p2.show();
}
/*3.完善字符窜类,增加以下 9、运算符的重载:+、- 等,实现两个字符窜间的运算。*/
#include 10、 str(str &s1)
{
length=s1.length +1;
p=new char [length];
strcpy(p,s1.p);
}
~str()
{if(p) delete []p;}
friend str operator +(str &,str &);
friend str operator -(str &,str &);
void operator =(str &);
void show()
{cout<<"length="< 11、r +(str &a,str &b)
{
str s;
s.length=a.length+b.length;
s.p=new char[s.length+1];
s.p=strcpy(s.p,a.p);
strcat(s.p,b.p);
return s;
}
str operator -(str &a,str &b)
{
str s;
char *p1=a.p,*p2;
int i=0,len=strlen(b.p);
if(p2=strstr(a.p,b.p)){
s.length=a.length-len;
s.p=new c 12、har[s.length+1];
while(p1 13、p,a.p);
}
void main()
{
char *a="I am a ",*b="student!";
str A(a),B(b),C;
C=A+B;
C.show();
C=C-B;
C.show();
}
/*附加题
定义一个字符窜类,用来存放不定长的字符窜,重载运算符"= ="、"<"、">",用于两个字符窜的等于、小于和大于的比较运算。*/
#include 14、ar *s)
{p=s;}
friend bool operator >(str &,str &);
friend bool operator <(str &,str &);
friend bool operator ==(str &,str &);
void show()
{
cout< (str &a,str &b)
{
if(strcmp(a.p,b.p)>0) return 1;
else return 0;
}
bool operator <(str &a,str &b)
{
if 15、strcmp(a.p,b.p)<0) return 1;
else return 0;
}
bool operator ==(str &a,str &b)
{
if(strcmp(a.p,b.p)==0) return 1;
else return 0;
}
void main()
{
char *a="I am a student!",*b="I love China!",*c="I love China!";
str A(a),B(b),C(c);
if(A>B) A.show();
else B.show();
if(A






