1 面向对象(C++)程序设计 (上机考试) 样题1
下列Shape 类是一个表示形状的抽象类,Area()为求图形面积的函数,Total()则是一个通用的用以求不同形状的图形面积总和函数
请从Shape 类派生三角形类(triangle) 、 矩形类(rectangle),并给出具体的求面积函数
编写程序验证求面积函数的正确性
Shape、 total 的定义如下所示
Class shape{ Pubilc: Virtual float area()=0 }; float total (shape *s[ ], int n) { float sum=0
0; for(int i=0; iarea (); return sum; } 解答: #include class shape{ public: virtual float area()=0; }; float total(shape *s[], int n) { float sum=0; for(int i=0; i area(); return sum; } class triangle : public shape{ protected: float H, W; public: triangle(float h, float w) { H=h; W=w;} float area() { return H*W*0
5;} }; class rectangle : public triangle{ public: rectangle(float h, float w) : triangle(h, w) {} float area() { return H*W;} }; void main() { shape *s[4]; s[0] = new triangle( 3
0 ); s[1] = new rec