7.试定义 RECT 类(长方形)及其派生类 CUB(长方体),具体要求如下:
- 类 RECT 的成员如下:
保护数据成员:
- double x,y; 分别表示长方形的长和宽。
公有成员函数: - RECT(double x1,double y1);构造函数,分别用 x1、 y1 初始化 x 和 y。
- virtual double area( ); 虚函数,计算长方形的面积,计算公式:面积=长×宽。
- double peri( ); 计算长方形的周长。计算公式:周长=2×长+2×宽。
- virtual int isSquare( ); 虚函数,判断是否为正方形,如是,返回 1;否则返回 0。
- 类 CUB 为类 RECT 的公有派生类,其成员如下:
私有数据成员:
- double height; 表示长方体的高度。
公有成员函数: - CUB( ); 构造函数,用 h、 x、 y 分别初始化 height 及其基类成员 x 和 y。
- double volume( ); 计算长方体的体积。计算公式:体积=底面积×高,其中底面积通过调用基类成员函数 area( )计算。
- double area(); 计算长方体的表面积。计算公式:表面积=2×底面积+底面周长×高度。底面积和底面周长分别调用基类成员函数 area()和 peri()计算。
- int isSquare();判断是否为正方体,如是,返回 1,否则返回 0。在判断过程中,首先调用基类的成员函数 isSquare()判断底面是否为正方形。
- 在主函数中,创建一个 CUB 对象 cu 和一个 RECT 指针*re,并使 re 指向 cu。通过 cu 调用 volume(),计算并输出长方体的体积;通过 re 调用 area()和 isSquare(),计算并输出长方体的表面积,并判断是否为下方体。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44#include<iostream> using namespace std; class RECT{ protected: double x,y; public: RECT(double x1,double y1):x(x1),y(y1){} virtual double area(){ return x*y; } double peri(){ return 2*(x+y); } virtual int isSquare(){ return x==y?1:0; } }; class CUB:public RECT{ double height; public: CUB(int h,int x,int y):RECT(x,y),height(h){} double volume(){ return height*RECT::area(); } virtual double area(){ return RECT::area()*2+RECT::peri()*height; } virtual int isSquare(){ return RECT::isSquare()&&x==height?1:0; } }; int main() { CUB cu(3,3,3); RECT *re=&cu; cout<<"volume of rect:"<<cu.volume()<<endl; cout<<"area of rect:"<<re->area()<<endl; if(re->isSquare()) cout<<"is cuben"; else cout<<"is not cuben"; return 0; }
最后
以上就是舒适鸵鸟最近收集整理的关于C++面向对象编程题 第7题的全部内容,更多相关C++面向对象编程题内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复