4.25
问题描述:
定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,并求出它们的和。要求用基类指针数组。使它的每一个元素指向一个派生类的对象。PI=3.1415926
输入格式:
例如:输入在一行中给出9个大于0的数,用空格分隔,分别代表圆的半径,正方形的边长,矩形的宽和高,梯形的上底、下底和高,三角形的底和高。
输出格式:
例如:输出所有图形的面积和,小数点后保留3位有效数字。
代码示例:
#include<iostream> using namespace std; #define PI 3.14159 class Shape { protected: double a, b, c; public: Shape(double a=0,double b=0,double c=0) { this->a = a; this->b = b; this->c = c; } virtual double getmianji() = 0; }; class Circle:public Shape{ public: Circle(double a) :Shape(a) {} double getmianji(){ return PI * a * a; } }; class Square :public Shape { public: Square(double a) :Shape(a) {} double getmianji(){ return a * a; } }; class Rectangle :public Shape{ public: Rectangle(double a,double b) :Shape(a,b) {} double getmianji() { return a*b; } }; class Trapezoid :public Shape{ public: Trapezoid(double a,double b,double c) :Shape(a,b,c) {} double getmianji(){ return (a + b) * c * 0.5; } }; class Triangle :public Shape//(三角形) { public: Triangle(double a,double b) :Shape(a,b) {} double getmianji(){ return a*b*0.5; } }; int main(){ double a, b, c; cin >> a; Circle C(a); cin >> a ; Square s(a); cin >> a >> b; Rectangle r(a, b); cin >> a >> b >> c; Trapezoid t1(a, b, c); cin >> a >> b; Triangle t2(a, b); Shape* sp[5] = { &C,&s,&r,&t1,&t2 }; double sum = 0; for (int i = 0; i < 5; i++) { sum += sp[i]->getmianji(); } printf("total of all areas = %0.3f", sum); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)