1. 程式人生 > >對於C++多態性的認識

對於C++多態性的認識

http views 項目 art tails 就是 ng- lai wid

1.說在前面:

項目大體上解決了,現在可以騰出時間來優化項目和學習新的知識

2.C++多態性

1.簡述:(多態)polymorphism

對於C++的多態性,這是一項很靈活的技術,用法十分靈巧,有難度;簡單來說:多態性就是適當的使用接口函數,通過一個接口來使用多種方法,(相當於上級說一個命令,A,B,C,D等人都做出反應,一個命令,多個反應;

2.怎樣實現多態性

1.采用虛函數和指針來實現多態性

通過虛函數來定義要實現的方法,通過基類的指針指向不同的子類的虛函數方法

2.多態性的優點是實現接口的重用

3.虛函數:

1.虛函數采用關鍵字virtual修飾,虛函數允許子類重新去定義成員函數;

2.重寫(函數名一致,但是內容不一致)//又稱覆蓋(override)

3.重載(函數名一致,但是參數表列不一致)

4.多態性一般就是通過對虛函數進行重寫,然後用基類指針指向不同的子對象,調用不同的虛函數

4.代碼實現

[cpp] view plain copy
  1. #include<iostream>
  2. #include<stdlib.h>
  3. #include<string>
  4. using namespace std;
  5. class Ishape
  6. {
  7. public:
  8. //多態性實現需要虛方法
  9. virtual double get_Area() = 0;
  10. virtual string get_Name() = 0;
  11. };
  12. //定義類1 CCircle
  13. class CCircle :public Ishape
  14. {
  15. //聲明的時候需要帶上Virtual關鍵字 顯示多態性
  16. public:
  17. CCircle(double radius) {this->c_radius = radius;}
  18. CCircle(){}
  19. virtual double get_Area();
  20. virtual string get_Name();
  21. private:
  22. double c_radius;//定義圓的半徑
  23. };
  24. //定義方法
  25. double CCircle::get_Area()
  26. {
  27. return 3.14*c_radius*c_radius;
  28. }
  29. string CCircle::get_Name()
  30. {
  31. return "CCircle";
  32. }
  33. class CRect :public Ishape
  34. {
  35. public:
  36. CRect(double length, double width) { this->m_length = length, this->m_width = width;}
  37. CRect(){};
  38. virtual double get_Area();
  39. virtual string get_Name();
  40. private:
  41. double m_length;
  42. double m_width;
  43. };
  44. double CRect::get_Area()
  45. {
  46. return m_length*m_width;
  47. }
  48. string CRect::get_Name()
  49. {
  50. return "Rectangle";
  51. }
  52. //通過指針指向不同的類從而使用不同的方法
  53. #include"text.h"
  54. void main()
  55. {
  56. <span style="white-space:pre;"> </span>Ishape *point = NULL;//建立指針
  57. <span style="white-space:pre;"> </span>point = new CCircle(10);
  58. <span style="white-space:pre;"> </span>//圓類
  59. <span style="white-space:pre;"> </span>cout << point->get_Name() << "的面積是:" << point->get_Area() << endl;
  60. <span style="white-space:pre;"> </span>delete point;
  61. <span style="white-space:pre;"> </span>//矩形類
  62. <span style="white-space:pre;"> </span>point = new CRect(10, 20);
  63. <span style="white-space:pre;"> </span>cout << point->get_Name() << "的面積是:" << point->get_Area() << endl;
  64. <span style="white-space:pre;"> </span>delete point;
  65. <span style="white-space:pre;"> </span>system("pause");
  66. }
  67. <span style="white-space:pre;"> </span>
  68. <span style="white-space:pre;"> </span>
  69. <span style="white-space:pre;"> </span>
  70. <span style="white-space:pre;"> </span>

對於C++多態性的認識