* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: 長方柱類數組
* 作 者: 楊森
* 完成日期: 2011 年 3 月 24 日
* 版 本 號: v1.0
【題目】編寫基於對象的程序,求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;
}