【sy1_类的实验_2_Box】

实验内容

(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;
}
3、运行结果:

image-20220908175124694

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值