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指向派生类对象circle 10 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 }
时间: 2024-10-29 00:50:51