实验7 运算符重载
(1)定义日期类,重载 “++”和“--”运算符,使之能处理两个日期类对象自增和自减运算,并且自增和自减又分为前缀和后缀运算。(可继续完善。。。博主太懒。。。不想写。。)
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
static int dys[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};
class date
{
int yr,mo,da;
public:
date(int y,int m,int d)
{
yr=y; mo=m; da=d;
}
date() {}
void disp()
{
cout<<yr<<"年"<<mo<<"月"<<da<<"日"<<endl;
}
isprime(int yr)
{
if(yr%4==0&&yr%100!=0||yr%400==0) return 1;
else return 0;
}
date operator + (int day)
{
date dt=*this;
day+=dt.da;
while(day>dys[isprime(yr)][dt.mo-1])
{
day-=dys[isprime(yr)][dt.mo-1];
dt.mo++;
if (dt.mo==13)
{
dt.mo==1;
dt.yr++;
}
}
dt.da=day;
return dt;
}
date operator - (int day)
{
date dt=*this;
day=dt.da-day;
while (day<=0)
{
day+=dys[isprime(yr)][dt.mo-1];
dt.mo--;
if (dt.mo==0)
{
dt.mo=12;
dt.yr--;
}
}
dt.da=day;
return dt;
}
};
int main()
{
int y,m,d,a,b;
cout<<"输入年月日:\n";
cin>>y>>m>>d;
date d1(y,m,d),d2,d3;
d1.disp();
cout<<"输入要加的天数(整数):";
cin>>a;
d2=d1+a;
d2.disp();
cout<<"输入要减的天数(整数):";
cin>>b;
d3=d1-b;
d3.disp();
return 0;
}
(2)定义复数类,重载复数的加“+”和“*” 运算符,完成复数的加法与乘法。
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
class complex
{
private:
float real;
float image;
public:
complex(float r=0,float i=0)
{
real=r;
image=i;
}
complex operator +(complex &obj)
{
complex c;
c.real=real+obj.real;
c.image=image+obj.image;
return c;
}
complex operator *(complex &obj)
{
complex c;
c.real=real*obj.real-image*obj.image;
c.image=image*obj.real+obj.image*real;
return c;
}
friend ostream & operator<<(ostream & ,complex &);
};
ostream & operator<<(ostream &out ,complex &obj)
{
out<<obj.real<<"+"<<obj.image<<"i"<<endl;
return out;
}
int main()
{
complex c1(3,4);
complex c2(c1);
complex c;
//加
c=c1+c2;
cout<<c<<endl;
//乘
c=c1*c2;
cout<<c<<endl;
return 0;
}