89.cpp

来自「c++课程习题集的源代码」· C++ 代码 · 共 75 行

CPP
75
字号
#include<iostream.h>
 const float PI=3.14;
 class shape
{
 public:
  shape(float x);
  virtual ~shape();
  virtual float get_area(void)=0;
 protected:
  float a;
};
 class rect:public shape
{
 public:
  rect(float x,float y);
  ~rect();
  float get_area(void);
 private:
  float b;
};
 class circle:public shape
{
 public:
  circle(float x);
  ~circle();
  float get_area(void);
};
 shape::shape(float x)
{
 a=x;
 cout<<"shape构造函数被调用"<<endl;
}
 shape::~shape()
{
 cout<<"shape析构函数被调用"<<endl;
}
 rect::rect(float x,float y):shape(x)
{
 b=y;
 cout<<"rect构造函数被调用"<<endl;
}
 rect::~rect()
{
 cout<<"rect析构函数被调用"<<endl;
}
 float rect::get_area(void)
{
 float s;
 s=a*b;
 return(s);
}
 circle::circle(float x):shape(x)
{
 cout<<"circle构造函数被调用"<<endl;
}
 circle::~circle()
{
 cout<<"circle析构函数被调用"<<endl;
}
 float circle::get_area(void)
{
 float s;
 s=PI*a*a;
 return(s);
}
 int main()
{
 int i;
 rect s(3,4);
 circle t(2);
 shape *p[2]={&s,&t};
 for(i=0;i<2;i++)
  cout<<p[i]->get_area()<<endl;
 return(0);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?