【6.13】 定义基类Base,其数据成员为高h,定义成员函数disp为虚函数。然后再由High派生出长方体类Cuboid与圆柱体类Cylinder。并在两派生类中定义成员函数disp为虚函数。在主函

来源:互联网 发布:淘宝促销词语 编辑:程序博客网 时间:2024/05/29 01:56

#include <iostream>
 using namespace std;
 class Base{
 protected:
double h;
 public:

Base(double h1)
{  
h=h1;
}
virtual void disp()=0;
 };
 class cuboid:public Base{
 private:
double wid,len;
 public:
cuboid(double l,double w,double h1):Base(h1)
{    len=l;
    wid=w;
}
    
void disp()
{  cout<<"cuboid:"<<endl;
  cout<<"extent:  "<<len<<endl;
  cout<<"width:  "<<wid<<endl;
  cout<<"height:  "<<h<<endl;
  cout<<"The bulk of cuboid is :  "<<len*wid*h<<endl;
}
 };
 class Cylinder:public Base{
 private:
double r;
 public:
Cylinder(double h1,double r1):Base(h1)
{   r=r1;
}
void disp()
{    cout<<"cylinder:"<<endl;
    cout<<"height:  "<<h<<endl;
    cout<<"radius:  "<<r<<endl;
    cout<<"The bulk of cylinder is :  "<<3.1415*r*r*h<<endl;
}
 };
 int main()
 {   Base *p;

cuboid cu(4,7,5);
Cylinder cy(6,9);
p=&cy;
p->disp();
p=&cu;
p->disp();
system("pause");
return 0;
 }

运行结果:


0 0