第4周项目3对象数组操作长方柱类

/*。
*Copyright(c)2014,烟台大学计算机学院
*All right reserved,
*文件名:test.cpp
*作者:毕玉堂
*完成日期:2015年4月3日
*版本号:v1.0
*
问题描述:
*输入描述:
*程序输出:
*/
#include <iostream>

using namespace std;
class Bulk
{
private:
    double length,width,heigth;
public:
    Bulk(double l=1.0,double w=1.0,double h=1.0):length(l),width(w),heigth(h){};
    void get_value();
    void output();
};
void Bulk::get_value()
{
    cin>>length>>width>>heigth;
}
void Bulk::output()
{
    cout<<"volume"<<" "<<length*width*heigth<<" ";
    cout<<"area"<<" "<<((length*width)*2+(length*heigth)*2+(width+heigth)*2)<<endl;
}
int main()
{
     Bulk b[5]={Bulk(2.3,4.5,6.7),Bulk(1.5,3.4),Bulk(10.5)};
     b[4].get_value();
     //下面分别输出这5个长方柱的体积和表面积
     b[0].output();
     b[1].output();
     b[2].output();
     b[3].output();
     b[4].output();
     return 0;
}

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是代码实现: ```c++ #include <iostream> #include <cmath> using namespace std; // 基:图形 class Shape { public: virtual float getArea() = 0; // 计算面积 virtual float getPerimeter() = 0; // 计算 }; // 派生:圆形 class Circle : public Shape { private: float radius; // 半径 public: Circle(float r) : radius(r) {} float getArea() { return M_PI * radius * radius; } float getPerimeter() { return 2 * M_PI * radius; } }; // 派生方形 class Rectangle : public Shape { private: float length; // float width; // 宽 public: Rectangle(float l, float w) : length(l), width(w) {} float getArea() { return length * width; } float getPerimeter() { return 2 * (length + width); } }; // 派生:三角形 class Triangle : public Shape { private: float a; // 第一条边 float b; // 第二条边 float c; // 第三条边 public: Triangle(float a, float b, float c) : a(a), b(b), c(c) {} float getArea() { float p = (a + b + c) / 2; return sqrt(p * (p - a) * (p - b) * (p - c)); } float getPerimeter() { return a + b + c; } }; int main() { // 定义对象数组 Shape* shapes[] = { new Circle(2), new Rectangle(3, 4), new Triangle(3, 4, 5) }; int n = sizeof(shapes) / sizeof(shapes[0]); // 计算面积和 for (int i = 0; i < n; i++) { cout << "Shape " << i + 1 << ":" << endl; cout << "Area: " << shapes[i]->getArea() << endl; cout << "Perimeter: " << shapes[i]->getPerimeter() << endl << endl; } // 释放内存 for (int i = 0; i < n; i++) { delete shapes[i]; } return 0; } ``` 在这个程序中,我们定义了一个抽象的基 `Shape`,并分别派生出了 `Circle`、`Rectangle` 和 `Triangle` 三个。在这些派生中,我们重写了基中的两个纯虚函数 `getArea()` 和 `getPerimeter()`,以计算每个图形的面积和。在 `main()` 函数中,我们定义了一个包含指向不同图形对象的指针的数组,并使用循环计算了每个对象的面积和。最后,我们释放了数组中每个对象的内存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值