C++_day8pm_多态
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 }
协变类型只能是指针或者引用,不能是对象。
纯抽象类:
全部由纯虚函数构成的抽象类称为纯抽象类或者接口。
动态: 编译阶段产生,运行阶段执行。
1 //模板方法模式---好莱坞模式 2 #include <iostream> 3 4 using namespace std; 5 6 class Parser{ 7 public: 8 void parse(char const* filename) 9 { 10 cout << "开始解析" << filename << "文件..." << endl; 11 drawText(); 12 drawCircle(); 13 drawRectangle(); 14 drawImage(); 15 cout << "解析" << filename << "文件完成!" << endl; 16 } 17 18 private: 19 virtual void drawText(void) = 0; 20 virtual void drawCircle(void) = 0; 21 virtual void drawRectangle(void) = 0; 22 virtual void drawImage(void) = 0; 23 24 }; 25 26 class Render: public Parser{ 27 private: 28 void drawText(void) 29 { 30 cout << "绘制文字..." << endl; 31 } 32 void drawCircle(void) 33 { 34 cout << "绘制圆形..." << endl; 35 } 36 void drawRectangle(void) 37 { 38 cout << "绘制矩形..." << endl; 39 } 40 void drawImage(void) 41 { 42 cout << "绘制图像..." << endl; 43 } 44 }; 45 46 int main(void) 47 { 48 Render render; 49 render.parse("stdc++.pdf"); 50 51 return 0; 52 }
注:虚表放在类中,虚表指针放在对象中。