}
private:
doublemonthlypay;
};
(4)intmain()
{
Salesmans1(1234,"ÀîÈð");
Salesmanagers2(1357,"ÎÄÇ¿");
s1.pay();
s1.print();
s2.pay();
s2.print();
return0;
}
第十章
1.定义一个辅助类Complex,重载运算符+、-、*、/使之能用于复数的加减乘除运算。
运算符重载函数为Complex类的成员函数。
编写程序,分别求出两个复数之和、差、积、商。
解:
#include
usingnamespacestd;
classComplex
{
public:
Complex(doubler=0.0,doublei=0.0){real=r;imag=i;}
Complexoperator+(Complex);
friendComplexoperator-(Complex,Complex);
Complexoperator*(Complex);
friendComplexoperator/(Complex,Complex);
voiddisplay();
private:
doublereal,imag;
};
ComplexComplex:
:
operator+(Complexc)
{
returnComplex(real+c.real,imag+c.imag);
}
Complexoperator-(Complexc1,Complexc2)
{
returnComplex(c1.real-c2.real,c1.imag-c2.imag);
}
ComplexComplex:
:
operator*(Complexc)
{
returnComplex(real*c.real-imag+c.imag,imag*c.imag+real*c.real);
}
Complexoperator/(Complexc1,Complexc2)
{
doubler,i;
r=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
i=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return(r,i);
}
voidComplex:
:
display()
{
cout<<"("<}
intmain()
{
Complexc1(7.1,8.4),c2(1.4,5),c3;
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
c3=c1+c2;
cout<<"c1+c2=";c3.display();
c3=c1-c2;
cout<<"c1-c2=";c3.display();
c3=c1*c2;
cout<<"c1*c2=";c3.display();
c3=c1/c2;
cout<<"c1/c2=";c3.display();
return0;
}
2.定义一个日期类Date,包括年,月,日等私有数据成员。
要求为所定义的Date类设计如下重载运算符函数:
Dateoperator+(intdays);返回一日起加天数days后得到的日期
Dateoperator-(intdays);返回一日起减天数days后得到的日期
Intoperator-(Date&b);返回两日期相差的天数
解:
#include
usingnamespacestd;
intday_tab[12]={31,28,31,30,31,30,31,31,30,31,30,31};
classDate
{
public:
Date(){}
Date(inty,intm,intd){year=y;mon=m;day=d;}
voidsetday(intd){day=d;}
voidsetmon(intm){mon=m;}
voidsetyear(inty){year=y;}
intgetday(){returnday;}
intgetmon(){returnmon;}
intgetyear(){returnyear;}
Dateoperator+(intdays)
{
staticDatedate;