实验内容
(2) 设计一个长方体类,它包含三个私有数据成员:长、宽、高;成员函数分别实现以下功能
①由键盘分别输人3个长方体的长、宽、高;
②计算长方体的体积;
③输出长方体的体积;
④计算长方体的表面积;
⑤输出长方体的表面积;
要求类的声明部分存放在一个单独的头文件(类名.h)中,类的成员函数实现存放在(类名.cpp)中,主函数存放在main.cpp中,在主函数中求验证以上成员函数的使用,从键盘录入长方体的长宽高,然后长方体的体积和表面积。
思路
1、操作步骤:
(1)Box类的声明: ·
class Box
{ //类的主体
private://静态属性==》类的数据成员
float length; //长
float width; //宽
float height; //高
public://动态功能==》类的函数成员
void get_value(); //静态属性的赋值
void volume(); //体积计算
void display_volume(); //体积输出
void s_area(); //表面积的计算
void display_s_area(); //表面积的输出
};
(2)动态功能的实现:
(a)静态属性的赋值
void Box::get_value(){
cout<<"请输入长方体的长宽高:"<<endl;
cout<<"长:";cin>>length;
cout<<"宽:";cin>>width;
cout<<"高:";cin>>height;
}
(b)体积的计算
void Box::volume(){
cout<<"体积V=("<<length<<"*"<<width<<"*"<<height<<")"<<endl;
}
(c)体积的输出
void Box::display_volume(){
cout<<"可得长方体体积为:"<<(length*width*height)<<endl;
}
(d)表面积的计算
void Box::s_area(){
cout<<"表面积S=("<<length<<"*"<<width<<"+"<<length<<"*"<<height<<"+"<<width<<"*"<<height<<")"<<"*2"<<endl;
}
(e)表面积的输出
void Box::display_s_area(){
cout<<"可得 长方体的表面积为:"<<(length*width*2+width*height*2+length*height*2)<<endl;
}
(3)长方体Box类的使用:
(a)Box类的使用主要包括两项工作:
- 定义该类对象
Box b1;
- 通过该对象调用类的成员(成员变量或成员函数)实现一定的功能
box1.get_value();
box1.volume();
box1.display_volume();
box1.s_area();
box1.display_s_area();
2、完整代码:
根据要求,需要将各段代码规范化整理。
Box.h
#include <iostream>
using namespace std;
class Box
{
private:
float length;
float width;
float height;
public:
void get_value();
void volume();
void display_volume();
void s_area();
void display_s_area();
};
void Box::get_value(){
cout<<"请输入长方体的长宽高:"<<endl;
cout<<"长:";cin>>length;
cout<<"宽:";cin>>width;
cout<<"高:";cin>>height;
}
void Box::volume(){
cout<<"体积V=("<<length<<"*"<<width<<"*"<<height<<")"<<endl;
}
void Box::display_volume(){
cout<<"可得长方体体积为:"<<(length*width*height)<<endl;
}
void Box::s_area(){
cout<<"表面积S=("<<length<<"*"<<width<<"+"<<length<<"*"<<height<<"+"<<width<<"*"<<height<<")"<<"*2"<<endl;
}
void Box::display_s_area(){
cout<<"可得 长方体的表面积为:"<<(length*width*2+width*height*2+length*height*2)<<endl;
}
Box_main.cpp
#include <iostream>
#include "Box.h"
using namespace std;
int main(){
Box box1;
box1.get_value();
box1.volume();
box1.display_volume();
box1.s_area();
box1.display_s_area();
return 0;
}