题目:编程完成下面功能。声明一个Shape(形状)基类,它有两个派生类:Circle(圆)和Square(正方形),要求利用多态性的概念,分别以虚函数的形式完成对圆和正方形的周长及面积的计算。
//shape.h
#ifndef SHAPE_H_INCLUDED
#define SHAPE_H_INCLUDED
class Shape
{
public:
Shape(double a, double b): point1(a),point2(b){}
virtual double getarea() const = 0;
virtual double getcir( )const = 0;
double point1;
double point2;
};
#endif // SHAPE_H_INCLUDED
//circle.h
#ifndef CIRCLE_H_INCLUDED
#define CIRCLE_H_INCLUDED
#include"shape.h"
class Circle: public Shape
{
double r;
public:
Circle(double a,double b,double e):Shape(a,b),r(e){}
virtual double getarea() const
{
return 3.14*r*r;
}
virtual double getcir() const
{
return 3.14*2*r;
}
};
#endif // CIRCLE_H_INCLUDED
//square.h
#ifndef SQURE_H_INCLUDED
#define SQURE_H_INCLUDED
#include"shape.h"
class Square: public Shape
{
double point5;
double point6;
public:
Square(double a,double b,double f, double g):Shape(a,b), point5(f), point6(g){}
virtual double getarea() const
{
return ((point5-point1)*2)*((point5-point1)*2);
}
virtual double getcir() const
{
return (point6-point2)*8;
}
};
#endif // SQURE_H_INCLUDED
//main.cpp
#include<iostream>
#include"shape.h"
#include"circle.h"
#include"squre.h"
using namespace std;
int main()
{
Circle c(3, 4, 2);
Square s(0, 0, 1, 1);
cout << c.getarea() << " " << c.getcir() << endl;
cout << s.getarea() << " " << s.getcir() << endl;
}