temp.a=a/x.a;
returntemp;
}
IntegerInteger:
:
operator=(Integerx)
{a=x.a;
return*this;
}
intmain()
{IntegerA(90),B(30),C;
cout<<"A=";A.display();
cout<<"B=";B.display();
C=A+B;
cout<<"C=A+B=";C.display();
C=A-B;
cout<<"C=A-B=";C.display();
C=A*B;
cout<<"C=A*B=";C.display();
C=A/B;
cout<<"C=A/B=";C.display();
}
11.使用虚函数编写程序求球体和圆柱体的体积及表面积。
由于球体和圆柱体都可以看做由圆继承而来,所以可以把圆类Circle作为基类。
在Circle类中定义一个数据成员radius和两个虚函数area和volume。
由Circle类派生Sphere类和Column类。
在派生类中对虚函数area和volume重新定义,分别求球体和圆柱体的体积及表面积。
【解答】
#include
usingnamespacestd;
constdoublePI=3.14159265;
classcircle
{public:
circle(doubler){radius=r;}
virtualdoublearea(){return0.0;}
virtualdoublevolume(){return0.0;}
protected:
doubleradius;
};
classsphere:
publiccircle
{public:
sphere(doubler):
circle(r){}
doublearea()
{return4.0*PI*radius*radius;}
doublevolume()
{return4.0*PI*radius*radius*radius/3.0;}
};
classcolumn:
publiccircle
{public:
column(doubler,doubleh):
circle(r){height=h;}
doublearea()
{return2.0*PI*radius*(height+radius);}
doublevolume()
{returnPI*radius*radius*height;}
private:
doubleheight;
};
intmain()
{circle*p;
spheresobj
(2);
p=&sobj;
cout<<"球体:
"<cout<<"体积="<volume()<cout<<"表面积="<area()<columncobj(3,5);
p=&cobj;
cout<<"圆柱体:
"<cout<<"体积="<volume()<cout<<"表面积="<area()<}
12.某学校对教师每月工资的计算规定如下:
固定工资+课时补贴。
教授的固定工资为5000元,每个课时补贴50元。
副教授的固定工资为3000元,每个课时补贴30元。
讲师的固定工资为2000元,每个课时补贴20元。
定义教师抽象类,派生不同职称的教师类,编写程序求若干个教师的月工资。
【解答】
#include
usingnamespacestd;
classteacher
{public:
teacher(chartname[],inttime)
{strcpy(name,tname);
coursetime=time;
}
virtualintpay()=0;
virtualvoidprint()=0;
char*getname()
{returnname;}
intgetcoursetime()
{returncoursetime;}
protected:
charname[30];
intcoursetime;
};
classprofessor:
publicteacher
{public:
professor(charpname[],inttime):
teacher(pname,time){}
intpay()
{return5000+coursetime*50;}
voidprint()
{cout<<"教授:
"<};
classassociateprofessor:
publicteacher
{public:
associateprofessor(charpname[],inttime):
teacher(pname,time){}
intpay()
{return3000+coursetime*30;}
voidprint()
{cout<<"副教授:
"<};
classlecturer:
publicteacher
{public:
lecturer(charpname[],inttime):
teacher(pname,time){}
intpay()
{return2000+coursetime*20;}
voidprint()
{cout<<"讲师:
"<};
intmain()
{professorpobj("李小平",32);
pobj.print();
cout<<'\t'<<"工资:
"<associateprofessorapobj("王芳芳",56);
apobj.print();
cout<<'\t'<<"工资:
"<lecturerlobj("何大建",72);
lobj.print();
cout<<'\t'<<"工资:
"<}