问答题 [说明]
以下C++代码使用虚函数实现了同一基类shape派生出来的Class rectangle、Class triangle、Class circle实现了计算矩形、圆形面积的计算。仔细阅读以下代码,将 (n) 处语句补充完整。
[代码5-1]
#include<iostream.h>
#define PI 3.14159
class shape //基类
protected:
(1)
public:
(2)
(3)

[代码5-2]
class rectangle: public shape
public:
rectangle (int x2,int y2,int r2): (4) ;
double area ( ) return x*y; ;
;
class circle: public shape
public:
circle (int x3,int y3,int r3): (5) ;
double area ( ) return r*r*PI; ;
;
[代码5-3]
void main ( )

rectangle r (10,20,0);
circle c (0,0,30);
shape (6)
cout<<"长方形面积="<<s1->area ( ) <<endl;
cout<<"圆形面积="<<s2->area ( ) <<endl;

[运行结果]
长方形面积=200
圆形面积=2827.43

【正确答案】(1)intx,y,r;
(2)shape (int x1,int y1,int r1): x(x1),y(y1),r(r1){};
(3)double virtual area ()=0;
(4)shape (x2,y2,r2)
(5)shape (x3,y3,r3)
(6)*s1=&r,*s2=&c;
【答案解析】[解析]
本题C++代码使用虚函数用同一基类shape派生出来的Class rectangle、Class triangle、Class circle实现了计算矩形、圆形面积的计算。各空实现的功能是:(1)x,y存储长与宽,r存储半径;(2)构造函数;(3)面积虚函数,旨在定义不同面积公式;(4)构造函数;(5)构造函数;(6)类变量定义,根据下文用到的变量可推知。