c++例題 建構函式(二)

來源:互聯網
上載者:User

題目來自: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;}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.