题目描述:
通过课程进入 题 号: 67 C++Test_Shape 语言要求: C++
已知基类定义在头文件ShapeFactory.h中,类定义如下:
#pragma once
class ShapeFactory
{
public:
ShapeFactory(){};
virtual ~ShapeFactory(){};
virtual float Circumstance(){return 0;};
ShapeFactory *Create(float a,float b,float c);
ShapeFactory *Create(float a,float b,float c,float d);
ShapeFactory *Create(float r);
};
请写出三角形、四边形、圆形三个派生类,构造函数分别传入三边/四边/半径的长度(不用检查是否符合三角形、矩形、圆的条件,没有异常输出),重写出求周长的函数(Circumstance函数)。
然后实现基类的Create函数,这里重载的三个Create函数,分别生成三角形、四边形、圆形的对象。
比如三角形类为Triangle:
ShapeFactory * ShapeFactory::Create(float a,float b,float c)
{
ShapeFactory *p=new Triangle(a,b,c);
return p;
}
实现:
#include<iostream>
#include"ShapeFactory.h"
using namespace std;
class Triangle :public ShapeFactory
{
private:
float a, b, c;
public:
Triangle(float a0, float b0, float c0)
{
a = a0; b = b0; c = c0;
}
float Circumstance()
{
return a + b + c;
}
};
class Quadrangle :public ShapeFactory
{
private:
float a, b, c, d;
public:
Quadrangle(float a0, float b0,float c0,float d0)
{
a = a0, b = b0, c = c0, d = d0;
}
float Circumstance()
{
return a + b + c+d;
}
};
class Circle :public ShapeFactory
{
private:
float r;
public:
Circle(float r0)
{
r = r0;
}
float Circumstance()
{
return r*2*3.14;
}
};
ShapeFactory* ShapeFactory::Create(float a, float b, float c)
{
ShapeFactory* p = new Triangle(a, b, c);
return p;
}
ShapeFactory* ShapeFactory::Create(float a, float b, float c, float d)
{
ShapeFactory* p = new Quadrangle(a, b, c, d);
return p;
}
ShapeFactory* ShapeFactory::Create(float r)
{
ShapeFactory* p = new Circle(r);
return p;
}