標籤: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):繼承和多態代碼實現