纯虚函数与基类指针数组的运用 代码参考
2020-04-30 16:00:38来源:博客园 阅读 ()
纯虚函数与基类指针数组的运用 代码参考
1 #include <iostream> 2 3 using namespace std; 4 5 class Shape 6 { 7 public: 8 virtual double printArea()=0; 9 virtual void printName()=0; 10 11 }; 12 13 class Circle:public Shape 14 { 15 private: 16 double r; 17 public: 18 Circle(double r){this->r=r;} 19 double printArea(){return 3.14159*r*r;} 20 void printName() 21 { 22 cout<<"圆:半径="<<r<<",面积:"<<printArea()<<endl; 23 } 24 }; 25 26 class Square:public Shape 27 { 28 private: 29 double a; 30 public: 31 Square(double a){this->a=a;} 32 double printArea(){return a*a; } 33 void printName() 34 { 35 cout<<"正方形:边长="<<a<<",面积:"<<printArea()<<endl; 36 } 37 }; 38 39 class Rectangle:public Shape 40 { 41 private: 42 double a,b; 43 public: 44 Rectangle(double a,double b){this->a=a;this->b=b;} 45 double printArea(){return a*b;} 46 void printName() 47 { 48 cout<<"长方形:长="<<a<<",宽="<<b<<",面积:"<<printArea()<<endl; 49 } 50 }; 51 52 class Trapezoid:public Shape 53 { 54 private: 55 double a,b,c; 56 public: 57 Trapezoid(double a,double b,double c){this->a=a;this->b=b;this->c=c;} 58 double printArea(){return (a+b)*c*0.5;} 59 void printName() 60 { 61 cout<<"梯形:上底="<<a<<",下底="<<b<<",高="<<c<<",面积:"<<printArea()<<endl; 62 } 63 }; 64 65 class Triangle:public Shape 66 { 67 private: 68 double a,b; 69 public: 70 71 Triangle(double a,double b){this->a=a;this->b=b;} 72 double printArea(){return a*b*0.5;} 73 void printName() 74 { 75 cout<<"三角形:底边="<<a<<",高="<<b<<",面积:"<<printArea()<<endl; 76 } 77 }; 78 79 int main() 80 { 81 double r,x,a,b,m,n,l,s,h; 82 double area=0.0; 83 cin>>r>>x>>a>>b>>m>>n>>l>>s>>h; 84 Shape *p[5]; 85 p[0]=new Circle(r); 86 p[1]=new Square(x); 87 p[2]=new Rectangle(a,b); 88 p[3]=new Trapezoid(m,n,l); 89 p[4]=new Triangle(s,h); 90 for(int i=0;i<5;i++) 91 { 92 p[i]->printName(); 93 area+=p[i]->printArea(); 94 } 95 cout<<"总面积:"<<area<<endl; 96 return 0; 97 }
原文链接:https://www.cnblogs.com/Conan-jine/p/12806847.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:STL之list
- C++ 转换函数搭配友元函数 2020-06-10
- C++ rand函数 2020-06-10
- C++ 友元函数 2020-06-10
- C++ const成员函数 2020-06-03
- C++ 析构函数 2020-06-03
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash