首页 > 其他分享 >7-5

7-5

时间:2023-03-16 22:55:56浏览次数:28  
标签: getArea double width length public Rectangle

定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。

 1 #include <iostream>
 2 #include <string>
 3 #include<string.h>
 4 #include <stdio.h>
 5 using namespace std;
 6 
 7 class Shape{
 8 public:
 9     virtual double getArea(){return -1;}
10 };
11 
12 class Rectangle:public Shape{
13 private:
14     double length;
15     double width;
16 public:
17     Rectangle(){length = 1; width = 1;}
18     Rectangle(double length, double width):length(length), width(width){}
19     double getArea(){return length * width;}
20     ~Rectangle(){}
21 };
22 
23 class Circle:public Shape{
24 private:
25     double r;
26 public:
27     Circle(){r = 1;}
28     Circle(double r):r(r){}
29     double getArea(){return 3.14 * r * r;}
30     ~Circle(){}
31     
32 };
33 
34 class Square:public Rectangle{
35 private:
36     double length;
37 public:
38     Square(){length = 1;}
39     Square(double len):length(len){}
40     double getArea(){return length * length;}
41     ~Square(){}
42 };
43 
44 
45 int main(){
46     Shape *test = new Rectangle(1,10);
47     cout<<"矩形面积:"<<test->getArea()<<endl;
48     delete test;
49     test = new Circle(10);
50     cout<<"圆形面积:"<<test->getArea()<<endl;
51     delete test;
52     test= new Square(5);
53     cout<<"正方形面积:"<<test->getArea()<<endl;
54     delete test;    
55     return 0;
56     
57 }

 

标签:,getArea,double,width,length,public,Rectangle
From: https://www.cnblogs.com/YUZE2001/p/17224551.html

相关文章