用对象数组操作长方柱类

来源:互联网 发布:ubuntu u盘启动 编辑:程序博客网 时间:2024/05/16 10:53
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Bulk  
  5. {  
  6. public:  
  7.     Bulk(double x = 1.0,double y = 1.0,double z = 1.0):length(x),width(y),height(z)//构造函数  
  8.     {volume = length*width*height;surface_area = length*length + width*width  + height*height;}  
  9.   
  10.     void get_value();  
  11.     void output();  
  12.     void calculate();  
  13. private:  
  14.     double length,width,height;  
  15.     double volume,surface_area;  
  16. };  
  17.   
  18. void Bulk::get_value()  
  19. {  
  20.     cout << "请输入长、宽、高:" << endl;  
  21.     cin >> length >> width >> height;  
  22. }  
  23.   
  24. void Bulk::output()  
  25. {  
  26.     cout << "体积:" << volume << "  " << "表面积:" << surface_area << endl;  
  27. }  
  28.   
  29. void Bulk::calculate()  
  30. {  
  31.     volume = length*width*height;  
  32.     surface_area = length*length + width*width  + height*height;  
  33. }  
  34.   
  35. int main()  
  36. {  
  37.     Bulk b[5] = {Bulk(2.3,4.5,6.7),Bulk(1.5,3.4),Bulk(10.5)};  
  38.     b[4].get_value();  
  39.     for(int i = 0; i < 5; ++i)  
  40.     {  
  41.         b[i].calculate();  
  42.         b[i].output();  
  43.     }  
  44.     return 0;  
  45. }  
0 0