2023 4 27
2 #include <iostream> 3 #include <string> 4 using namespace std; 5 class Shape 6 { 7 virtual void setvalues() = 0; 8 virtual void floatarea() = 0; 9 }; 10 class rectangle:public Shape 11 { 12 public: 13 void setvalues() 14 { 15 cout<<"请输入矩形的底和高:"<<endl; 16 cin>>x>>y; 17 } 18 void floatarea() 19 { 20 cout<<"矩形的面积为:"<<x*y<<endl; 21 } 22 float x; 23 float y; 24 }; 25 class arctangle:public Shape 26 { 27 public: 28 void setvalues() 29 { 30 cout<<"请输入三角形的底和高:"<<endl; 31 cin>>x>>y; 32 } 33 void floatarea() 34 { 35 cout<<"三角形的面积为:"<<x*y/2<<endl; 36 } 37 float x; 38 float y; 39 }; 40 class square:public Shape 41 { 42 public: 43 void setvalues() 44 { 45 cout<<"请输入正方形的边长:"<<endl; 46 cin>>x; 47 } 48 void floatarea() 49 { 50 cout<<"正方形的面积为:"<<x*x<<endl; 51 } 52 float x; 53 }; 54 class circle:public Shape 55 { 56 public: 57 void setvalues() 58 { 59 cout<<"请输入圆形的半径:"<<endl; 60 cin>>r; 61 } 62 void floatarea() 63 { 64 cout<<"圆形的面积为:"<<3.1415*r*r<<endl; 65 } 66 float r; 67 }; 68 void test() 69 { 70 rectangle r; 71 arctangle a; 72 square s; 73 circle c; 74 r.setvalues(); 75 a.setvalues(); 76 s.setvalues(); 77 c.setvalues(); 78 if(r.x<=0||r.y<=0||a.x<=0||a.y<=0||s.x<=0||c.r<=0) 79 { 80 cout<<"Set Value Error!"<<endl; 81 exit(0); 82 } 83 r.floatarea(); 84 a.floatarea(); 85 s.floatarea(); 86 c.floatarea(); 87 } 88 int main() 89 { 90 test(); 91 return 0; 92 }
1 #include <iostream> 2 using namespace std; 3 //利用多态,实现计算器 4 //多态的好处 5 //1、组织结构清晰 6 //2、可读性强 7 //3、对于前期和后期扩展以及维护性高 8 class AbstractCalculator 9 { 10 public: 11 int m_Num1; 12 int m_Num2; 13 virtual int getResult() 14 { 15 return 0; 16 } 17 }; 18 class AddCalculate : public AbstractCalculator 19 { 20 int getResult() 21 { 22 return m_Num1 + m_Num2; 23 } 24 }; 25 class SubCalculate : public AbstractCalculator 26 { 27 int getResult() 28 { 29 return m_Num1 - m_Num2; 30 } 31 }; 32 class MulCalculate : public AbstractCalculator 33 { 34 int getResult() 35 { 36 return m_Num1 * m_Num2; 37 } 38 }; 39 void test() 40 { 41 //创建加法计算器 42 AbstractCalculator *abc = new AddCalculate; 43 abc->m_Num1 = 10; 44 abc->m_Num2 = 10; 45 cout<<abc->m_Num1<<" + "<<abc->m_Num2<<" = "<<abc->getResult()<<endl; 46 delete abc; 47 //创建加法计算器 48 abc = new SubCalculate; 49 abc->m_Num1 = 10; 50 abc->m_Num2 = 10; 51 cout<<abc->m_Num1<<" - "<<abc->m_Num2<<" = "<<abc->getResult()<<endl; 52 //创建乘法计算器 53 abc = new MulCalculate; 54 abc->m_Num1 = 10; 55 abc->m_Num2 = 10; 56 cout<<abc->m_Num1<<" * "<<abc->m_Num2<<" = "<<abc->getResult()<<endl; 57 } 58 int main() 59 { 60 test(); 61 return 0; 62 }