C++筆記(5):繼承和多態代碼實現

來源:互聯網
上載者:User

標籤:virtual   ack   sha   類對象   span   rect   delete   冒號   end   

Shape.h

 1 #ifndef SHAPE_H 2 #define SHAPE_H 3 #include<string> 4 using std::string; 5  6 class IShape 7 { 8 public: 9     virtual float getArea()=0;10     virtual string getName()=0;11 };12 13 #endif

Circle.h

 1 #ifndef CIRCLE_H 2 #define CIRCLE_H 3 #include"Shape.h" 4 class CCircle : public IShape 5 { 6 public: 7     CCircle(float radius); 8 public: 9     virtual float getArea();10     virtual string getName();11 12 private:13     float m_fRadius;14 };15 16 #endif

Circle.cpp

 1 #include"Circle.h" 2  3 CCircle::CCircle(float radius) 4     :m_fRadius(radius)     //冒號表示初始化列表,m_fRadius表示變數名,radius表示變數初始值大小,注意不是繼承符號 5 { 6 } 7  8 float CCircle::getArea() 9 {10     return 3.14 * m_fRadius * m_fRadius;11 }12 13 string CCircle::getName()14 {15     return "CCircle";16 }

Rect.h

 1 #ifndef RECT_H 2 #define RECT_H 3 #include"shape.h" 4 class CRect : public IShape 5 { 6 public: 7     CRect(float nWidth, float nHeight); 8  9 public:10     virtual float getArea();11     virtual string getName();12 13 private:14     float  m_fWidth;15     float  m_fHeight;16 };17 18 19 #endif

Rect.cpp

 1 #include"Rect.h" 2  3 CRect::CRect(float fWidth, float fHeight) 4     :m_fWidth(fWidth), m_fHeight(fHeight)       //冒號同樣表示初始化列表,不是繼承符號,注意區分 5 { 6 } 7  8 float CRect::getArea() 9 {10     return m_fWidth * m_fHeight;11 }12 13 string CRect::getName()14 {15     return "CRect";16 }

 

main.cpp

 1 #include<iostream> 2 #include"Rect.h" 3 #include"Circle.h" 4 using namespace std; 5  6 int main() 7 { 8     IShape* pShape = NULL; 9     pShape = new CCircle(20.2);         //基類的指標pShape指向衍生類別對象circle10     cout<<pShape->getName()<<" "<<pShape->getArea()<<endl;11 12     delete pShape;13     pShape = new CRect(20, 10);     //基類的指標pShape指向衍生類別對象crect

14   cout<<pShape->getName()<<" "<<pShape->getArea()<<endl;
15
16   return 0;
17 }

 

C++筆記(5):繼承和多態代碼實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.