1.什么是多态
2.
示例代码:
1 #include <iostream> 2 3 using namespace std; 4 5 //形状:位置、绘制 6 //+--圆形:半径、(绘制) 7 //+--矩形:长宽、(绘制) 8 //形状 9 class Shape{ 10 public: 11 Shape(int x, int y): m_x(x), m_y(y){} 12 virtual void draw(void) const 13 { 14 cout << "形状(" << m_x << ',' << m_y << ')' << endl; 15 } 16 17 protected: 18 int m_x; 19 int m_y; 20 }; 21 22 //圆形 23 class Circle: public Shape{ 24 public: 25 Circle(int x, int y, int r): Shape(x, y), m_r(r){} 26 void draw(void) const 27 { 28 cout << "圆形(" << m_x << ',' << m_y << ',' << m_r << ')' << endl; 29 } 30 private: 31 int m_r; 32 }; 33 34 //矩形 35 class Rectangle: public Shape{ 36 public: 37 Rectangle(int x, int y, int w, int h): Shape(x, y), m_w(w), m_h(h){} 38 void draw(void) const 39 { 40 cout << "矩形(" << m_x << ',' << m_y << ',' << m_w << ',' << m_h << ')' << endl; 41 } 42 private: 43 int m_w; 44 int m_h; 45 }; 46 47 void render(Shape* shapes[]) 48 { 49 for(size_t i = 0; shapes[i]; ++i) 50 shapes[i]->draw(); 51 } 52 53 void drawAny(Shape const& shape) 54 { 55 shape.draw(); 56 } 57 58 int main(void) 59 { 60 Shape* shapes[10] = {0}; 61 shapes[0] = new Circle (1,2,3); 62 shapes[1] = new Circle(4,5,6); 63 shapes[2] = new Rectangle(7,8,9,10); 64 shapes[3] = new Rectangle(11,12,13,14); 65 shapes[4] = new Circle(15,16,17); 66 render(shapes); 67 /* 68 Circle c(18,19,20); 69 Shape& r = c; 70 r.draw(); 71 */ 72 Circle cr(18,19,20); 73 drawAny(cr); 74 Rectangle rc(21,22,23,24); 75 drawAny(rc); 76 77 return 0; 78 }
协变类型只能是指针或者引用,不能是对象。