11.7 上机实践习题
1.定义一个抽象类,然后将这个类作为基类,再派生两个子类,最后调用其中的虚函数显示输出数据。
【提示】上述题目主要是要求读者熟悉类继承的相关知识,重点是掌握继承的概念和作用。
【关键代码】
01 class base//基类定义 02 { 03 public: 04 virtual void disp()//虚函数 05 { 06 cout<<"hello,base"<<endl; 07 } 08 }; 09 class child1:public base//派生类定义 10 { 11 public: 12 void disp() 13 { 14 cout<<"hello,child1"<<endl; 15 } 16 }; 17 18 class child2:public base 19 { 20 public: 21 void disp() 22 { 23 cout<<"hello,child2"<<endl; 24 } 25 }; 26 27 void disp(base*p) 28 { 29 p->disp(); 30 }
2.定义一个抽象类Point,其中包括一个纯虚函数getArea(),然后派生两个子类CRect和CTrigon,最后在主函数中初始化并调用该虚函数输出结果。
【提示】上述题目主要是要求读者掌握纯虚函数的相关知识,重点是掌握纯虚函数的作用及其实现方法。
【关键代码】
01 class CPoint 02 { 03 public: 04 CPoint(float w,float h);//构造函数 05 virtual float getArea()=0;//求几何面积的纯虚函数 06 private: 07 float m_w,m_h; 08 }; 09 CPoint:CPoint(float w,float h) 10 { 11 m_w=w; 12 m_h=h; 13 } 14 15 class CRect:public CPoint 16 { 17 public: 18 CRect(float w,float h); 19 float getArea();//纯虚函数在子类中的声明 20 private: 21 float m_w,m_h; 22 }; 23 CRect:CRect(float w,float h) 24 :CPoint(w,h) 25 { 26 m_w=w; 27 m_h=h; 28 } 29 float CRect:getArea()//纯虚函数在子类中的实现 30 { 31 cout<<"调用CRect类的getArea成员函数"<<endl; 32 return m_w*m_h; 33 } 34 35 class CTrigon:public CPoint 36 { 37 public: 38 CTrigon(float f,float h); 39 float getArea();//纯虚函数在子类中的声明 40 private: 41 float m_f,m_h; 42 }; 43 CTrigon:CTrigon(float f,float h) 44 :CPoint(f,h) 45 { 46 m_f=f; 47 m_h=h; 48 } 49 float CTrigon:getArea()//纯虚函数在子类中的实现 50 { 51 cout<<"调用CTrigon类的getArea成员函数"<<endl; 52 return m_f*m_h/2; 53 } 54 55 void disp(CPoint*p) 56 { 57 cout<<"面积为:"<<p->getArea()<<endl; 58 }