【题目】编写基于对象的程序,求5个长方柱的体积和表面积。长方柱类的数据成员包括长(length)、宽(width)、高(heigth)等。另外:
(1)需要定义长方柱类,5个长方柱采用一个对象数组表示;
(2)前4个长方柱(即数组的前4个元素)要在定义数组时初始化,其中前3个直接给出参数初始化,第4、5个用默认构造函数初始化;然后第5个长方柱由键盘输入长、宽、高;
(3)输出这5个长方柱的体积和表面积
- #include <iostream>
- using namespace std;
- class Bulk
- {
- public:
- Bulk():lengh(1.0),width(1.0),height(1.0){};//默认构造函数
- Bulk(doublex,double y,doublez):lengh(x),width(y),height(z){};//带参数的构造函数
- void set_value();
- void display();
- private:
- double lengh;
- double width;
- double height;
- };
- void Bulk::set_value()
- {
- cout<<"please input lengh, width,height:";
- cin>>lengh;
- cin>>width;
- cin>>height;
- }
- void Bulk::display()
- {
- cout<<" The volume is: "<<lengh*width*height<<endl;
- cout<<" The surface area is: "<<2*(lengh*width+lengh*height+width*height)<<endl;
- cout<<endl;
- }
- int main()
- {
- Bulkb[5]={Bulk(2.3,4.5,6.7),Bulk(1.5,3.4,9.5),Bulk(10.5,22.3,3.14)};//前三个元素用带参构造函数初始化,后两个用默认构造函数
- b[4].set_value(); //注意b[4]是一个对象,调用成员函数的形式b[4].set_value()
- for(int i=0;i<5;++i)
- {
- cout<<"关于b["<<i<<"]"<<endl;
- b[i].display();//调用对象数组中元素的成员函数
- }
- system("pause");
- return 0;
- }