多态
Posted satellite&
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多态相关的知识,希望对你有一定的参考价值。
声明类Shape以及它的3个派生类:Circle、Square、Rectangle,用虚函数分别计算几种图形的面积、周长,编写程序,建立基类指针数组,每个指针均指向一个派生类对象,利用基类指针遍历元素对象,求取所有图形面积之和。请绘制UML类图。
1 //Shape.h 2 #ifndef _SHAPE_H_ 3 #define _SHAPE_H_ 4 5 class Shape 6 { 7 public: 8 virtual double S()=0; 9 virtual double C()=0; 10 }; 11 #endif 12 13 //Circle.h 14 #include "Shape.h" 15 16 class Circle:public Shape 17 { 18 public: 19 Circle(double ir); 20 double S(); 21 double C(); 22 private: 23 double r; 24 }; 25 26 //Circle.cpp 27 #include "Circle.h" 28 #include <iostream> 29 #define PI 3.14 30 31 using namespace std; 32 33 Circle::Circle(double ir) 34 { 35 r=ir; 36 cout<<"<construct a circle>"<<endl; 37 } 38 double Circle::S() 39 { 40 return (PI*r*r); 41 } 42 double Circle::C() 43 { 44 return (2*PI*r); 45 } 46 47 //Square.h 48 #include "Shape.h" 49 50 class Square:public Shape 51 { 52 public: 53 Square(double ia); 54 double S(); 55 double C(); 56 private: 57 double a; 58 }; 59 //Square.cpp 60 #include "Square.h" 61 #include <iostream> 62 63 using namespace std; 64 65 Square::Square(double ia) 66 { 67 a=ia; 68 cout<<"<construct a square>"<<endl; 69 } 70 double Square::S() 71 { 72 return (a*a); 73 } 74 double Square::C() 75 { 76 return(4.0*a); 77 } 78 79 //Rectangle.h 80 #include "Shape.h" 81 82 class Rectangle:public Shape 83 { 84 public: 85 Rectangle(double iw,double ih); 86 double S(); 87 double C(); 88 private: 89 double w; 90 double h; 91 }; 92 93 //Rectangle.cpp 94 #include "Rectangle.h" 95 #include <iostream> 96 97 using namespace std; 98 99 Rectangle::Rectangle(double iw,double ih) 100 { 101 w=iw; 102 h=ih; 103 cout<<"<construct a rectangle>"<<endl; 104 } 105 double Rectangle::S() 106 { 107 return (w*h); 108 } 109 double Rectangle::C() 110 { 111 return (2*(w+h)); 112 } 113 114 //main.cpp 115 #include <iostream> 116 #include "Circle.h" 117 #include "Square.h" 118 #include "Rectangle.h" 119 120 using namespace std; 121 122 int main() 123 { 124 int i=0; 125 double c,s; 126 double sum=0; 127 128 Circle circle1(1); 129 Square square1(2); 130 Rectangle rectangle1(3,4); 131 132 Shape * p[3]; 133 p[0]=&circle1; 134 p[1]=&square1; 135 p[2]=&rectangle1; 136 137 cout<<endl<<"Circle:"<<endl; 138 for(i=0;i<3;i++) 139 { 140 c=p[i]->C(); 141 cout<<"c"<<i<<"="<<c<<endl; 142 } 143 cout<<endl<<"Square:"<<endl; 144 for(i=0;i<3;i++) 145 { 146 s=p[i]->S(); 147 cout<<"s"<<i<<"="<<s<<endl; 148 sum+=s; 149 } 150 cout<<"total square="<<sum<<endl; 151 return 0; 152 }
1.error: redefinition of class Shape
使用宏定义防止头文件Shape.h被多次包含
#ifndef _SHAPE_H(有空格!否则unrecognized preprocessing directive:)
#define _SHAPE_H(有空格!)
class Shape {
//......
};
#endif
- 定义指针数组
类型 * p[n];
以上是关于多态的主要内容,如果未能解决你的问题,请参考以下文章