已知基类ShapeFactory的声明如下: const float pi=3.1416; 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); 请写出三角形(Triangle)、四边形(Quadrangle)、圆形(Circle)三个派生类,构造函数分别传入三边/四边/半径的长度(不用检查是否符合三角形、矩形、圆的条件,没有异常输出),重写出求周长的函数(Circumstance函数)。 然后实现基类的Create函数,这里重载的三个Create函数,分别生成三角形、四边形、圆形的对象。 比如三角形类为Triangle: ShapeFactory * ShapeFactory::Create(float a,float b,float c) { ShapeFactory *p=new Triangle(a,b,c); return p; } 如果三角形输入的三边长度是 3 4 5,四边形输入的四条边的长度是2 3 4 7,圆的半径是3,则要求程序运行能够得到如下的提示和输出:
时间: 2024-03-11 15:46:58 浏览: 125
现在将类A声明为虚基类方法如下:-谭浩强C++程序设计 1229页(ppt最新完整版)
三角形、四边形、圆形的派生类实现如下:
```c++
class Triangle : public ShapeFactory {
public:
Triangle(float a, float b, float c) : ShapeFactory(), side1(a), side2(b), side3(c) {}
virtual ~Triangle() {}
virtual float Circumstance() { return side1 + side2 + side3; }
private:
float side1, side2, side3;
};
class Quadrangle : public ShapeFactory {
public:
Quadrangle(float a, float b, float c, float d) : ShapeFactory(), side1(a), side2(b), side3(c), side4(d) {}
virtual ~Quadrangle() {}
virtual float Circumstance() { return side1 + side2 + side3 + side4; }
private:
float side1, side2, side3, side4;
};
class Circle : public ShapeFactory {
public:
Circle(float r) : ShapeFactory(), radius(r) {}
virtual ~Circle() {}
virtual float Circumstance() { return 2 * pi * radius; }
private:
float radius;
};
```
Create函数的实现如下:
```c++
ShapeFactory* ShapeFactory::Create(float a, float b, float c) {
return new Triangle(a, b, c);
}
ShapeFactory* ShapeFactory::Create(float a, float b, float c, float d) {
return new Quadrangle(a, b, c, d);
}
ShapeFactory* ShapeFactory::Create(float r) {
return new Circle(r);
}
```
然后在程序中调用即可:
```c++
int main() {
float a = 3, b = 4, c = 5;
ShapeFactory* p = ShapeFactory::Create(a, b, c);
cout << "三角形周长为:" << p->Circumstance() << endl;
delete p;
float side1 = 2, side2 = 3, side3 = 4, side4 = 7;
p = ShapeFactory::Create(side1, side2, side3, side4);
cout << "四边形周长为:" << p->Circumstance() << endl;
delete p;
float r = 3;
p = ShapeFactory::Create(r);
cout << "圆形周长为:" << p->Circumstance() << endl;
delete p;
return 0;
}
```
输出结果:
```
三角形周长为:12
四边形周长为:16
圆形周长为:18.8496
```
阅读全文