c++编写 shape类

来源:百度知道 编辑:UC知道 时间:2024/09/20 09:30:28
1、 设计一个Shape类,
a) Shape具有一个成员函数来计算面积,Shape具有数据成员,颜色,可通过成员函数设置和读取形状的颜色;
b) 设计一个point类,用于表示点;
c) 从shape类派生两个类,矩形和圆形;分别实现派生类的构造函数、析构函数和其他方法;矩形和圆形类中可使用point类来表示必要的对象;
d) 创建shape的指针数组,并初始化这些指针指向不同的矩形或者圆形对象,并通过对指针数组的循环遍历,来实现对各种对象基本信息以及面积的输出;

#include <iostream>
#include <math.h>
using namespace std;

#define PI 3.14
enum Colors{
Black,
White,
Orange,
Blue // etc...
};
class Shape{
public:
inline int Color() const
{return color;}
void SetColor(int color)
{this->color = color;}
virtual double Area() const=0;
private:
int color;
};
class Point{
public:
Point(double a, double b):x(a),y(b){}
double x;
double y;
};
class Rectangle : public Shape{
public:
Rectangle(double x, double y, double w, double h):
tl(x,y),br(x+w,y+h)
{
}
double Area() const
{return abs((tl.x - br.x)*(tl.y - br.y));}
private:
Point tl;
Point br;
};

class Circle: public Shape{
public:
Circle(double x, double y, double r):c(x,y){
this->r=r;
}

double Area() const{
return PI*r*