打卡 无规矩不成方圆 - C/C++ 多态

请结合如图所示的继承关系设计Shape、Circle以及Rectangle类,使得下述代码可以正确计算并输出矩形和圆的面积。

提示:Shape的析构以及area()函数都应为虚函数。

 

 

裁判测试程序样例:

//Project - Shapes
#include <iostream>
using namespace std;

//在此处定义Shape, Cirlce及Rectangle类

int main(){
    Shape* shapes[2];
    int w, h;
    cin >> w >> h;   //输入矩形的长宽
    shapes[0] = new Rectangle(w,h);
    float r;   //输入圆的半径
    cin >> r;
    shapes[1] = new Circle(0,0,2);  //圆心在(0,0),半径为r的圆
    printf("Area of rectangle:%.2f\n",shapes[0]->area());
    printf("Area of circle:%.2f\n",shapes[1]->area());
    for (auto i=0;i<2;i++)
        delete shapes[i];
    return 0;
}

解题思路:虚函数的重载与虚析构函数重载

class Shape{
public:
  Shape(){}
  virtual ~Shape(){}
  virtual float area()=0;
};
class Circle:public Shape{
private:
  int x, y;
  float radius;
public:
  Circle(int x, int y, float radius){
  this->x =x; this->y=y; this->radius=radius;
}
  ~Circle(){}
  float area(){
  return 3.1415926f*radius*radius;
}
};
class Rectangle:public Shape{
private:
  int width, heigth;
public:
  Rectangle(int w, int h){
  width=w; heigth=h;
}
~Rectangle(){}
  float area(){
  return width*heigth;
}
};



posted @ 2023-04-18 22:59  起名字真难_qmz  阅读(552)  评论(1)    收藏  举报