題目來自:http://blog.csdn.net/sxhelijian/article/details/8723847
【項目3】編寫基於對象的程式,求5個長方柱的體積和表面積。長方柱類Bulk的資料成員包括長(length)、寬(width)、高(heigth)等。另外:
(1)需要定義長方柱類,5個長方柱採用一個對象數組表示;
(2)定義相應的建構函式以支援如下main()函數中的初始化,其中前3個直接給出參數初始化(未給出的參數預設為1.0),第4個對象b[3]用預設建構函式初始化;第5個長方柱定義時不初始化,而是由鍵盤輸入長、寬、高賦值;
(3)輸出這5個長方柱的體積和表面積;
#include <iostream>using namespace std;class Bulk{private:double length;double width;double height;public:Bulk(double len = 1.0,double wid = 1.0,double hei = 1.0):length(len),width(wid),height(hei){} void get_value();double volume();double surface_are();};void Bulk::get_value(){cout <<"please input the length width and height: " << endl; cin >> length >> width >> height;}double Bulk::volume(){return length*width*height;}double Bulk::surface_are(){return 2*(length*width+width*height+height*length);}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個長方柱的體積和表面積cout << "第一個長方柱的體積: " << b[0].volume() << '\t' << " 面積: " << b[0].surface_are() << endl << "第二個長方柱的體積: " << b[1].volume() << '\t' << " 面積: " << b[1].surface_are() << endl << "第三個長方柱的體積: " << b[2].volume() << '\t' << " 面積: " << b[2].surface_are() << endl << "第四個長方柱的體積: " << b[3].volume() << '\t' << " 面積: " << b[3].surface_are() << endl << "第五個長方柱的體積: " << b[4].volume() << '\t' << " 面積: " << b[4].surface_are() << endl;return 0;}