长方柱类(对象数组)

    xiaoxiao2026-09-23  18

           编写基于对象的程序,求5个长方柱的体积和表面积。长方柱类Bulk的数据成员包括长(length)、宽(width)、高(heigth)等。   对照已经给出的代码,要做的工作及要求有:

    需要你定义长方柱类,代码中已经给出由5个长方柱对象构成的对象数组b;B数组中的前3个对象b[0]、b[1]、b[2]直接参数初始了,需要定义构造函数,而初始化中,各对象提供的参数数目不同,需要有默认参数的构造函数(未给出的参数默认为1.0)第4个对象b[3]用默认构造函数初始化;设计成员函数output,在main中调用输出这5个长方柱的体积和表面积;

    #include<iostream> #include<cmath> using namespace std; class Bulk { public: Bulk(double l=1.0,double w=1.0,double h=1.0):length(l),width(w),heigth(h){} double getAreas(); double getVolunm(); void output(); void get_value(); private: // double b[5]; double length; double width; double heigth; }; void Bulk::get_value() { int x,y,z; cin>>x>>y>>z; heigth=z; width=y; length=x; } double Bulk::getAreas() { return 2*(length*width+length*heigth+width*heigth); } double Bulk::getVolunm() { return length*width*heigth; } void Bulk::output() { cout<<"面积:"<<getAreas()<<endl; cout<<"体积:"<<getVolunm()<<endl; } int main() { Bulk b[5]={Bulk(2.3,4.5,6.7),Bulk(1.5,3.4),Bulk(10.5)}; cout<<"为第五个长方柱输入参数:"<<endl; b[4].get_value(); for(int i=0;i<5;i++) { cout<<"第"<<i+1<<"个长方柱的资料输出:"<<endl; b[i].output(); cout<<endl; } return 0; }

    运行结果:

    转载请注明原文地址: https://ju.6miu.com/read-1312247.html
    最新回复(0)