题目要求
需要求3个长方柱的体积,请编写一个基于对象的程序。数据成员包括 length(长)、widht(宽)、height(高)。要求用成员函数实现以下功能:
(1)由键盘分别输入3个长方柱的长、宽、高;
(2)计算长方柱的体积;
(3)输出3个长方柱的体积。
——谭浩强的《C++面向对象程序设计》第2章习题第6小题
程序
box.h
/*
************************************************************************
@file: box.h
@date: 2020.11.1
@author: Xiaoxiao
@brief: 定义Box类
@blog: https://blog.csdn.net/weixin_43470383/article/details/109412631
************************************************************************
*/
#include <iostream>
using namespace std;
class Box // 声明类类型
{
private: // 声明私有部分
int length; // 长方柱的长
int width; // 长方柱的宽
int height; // 长方柱的高
public: // 声明公用部分
// 类内声明成员函数
void set_value(); // 输入长方柱的长、宽、高
int volume(); // 输出长方柱的体积
};
box.cpp
/*
************************************************************************
@file: box.cpp
@date: 2020.11.1
@author: Xiaoxiao
@brief: 定义成员函数 set_value() 和 volume()
@blog: https://blog.csdn.net/weixin_43470383/article/details/109412631
************************************************************************
*/
#include"box.h"
// 类外定义成员函数
void Box::set_value() // 成员函数定义,由键盘分别输入长方柱的长、宽、高
{
cin >> length;
cin >> width;
cin >> height;
}
int Box::volume() // 成员函数定义,返回长方柱的体积
{
return (length * width * height);
}
main.cpp
/*
************************************************************************
@file: main.cpp
@date: 2020.11.1
@author: Xiaoxiao
@brief: 主函数
@blog: https://blog.csdn.net/weixin_43470383/article/details/109412631
************************************************************************
*/
#include "box.h"
int main()
{
Box Box1, Box2, Box3; // 定义Box类的对象Box1, Box2, Box3
cout << "pls input length, width and height of box1:" << endl;
Box1.set_value();
// 调用set_value()函数,由键盘分别输入Box1的长、宽、高
Box1.volume();
// 调用volume()函数,输出Box1的体积
cout << "The volume of box1 is:" << endl << Box1.volume() << endl << endl;
cout << "pls input length, width and height of box2:" << endl;
Box2.set_value();
// 调用set_value()函数,由键盘分别输入Box2的长、宽、高
Box2.volume();
// 调用volume()函数,输出Box2的体积
cout << "The volume of box2 is:" << endl << Box2.volume() << endl << endl;
cout << "pls input length, width and height of box3:" << endl;
Box3.set_value();
// 调用set_value()函数,由键盘分别输入Box3的长、宽、高
Box3.volume();
// 调用volume()函数,输出Box3的体积
cout << "The volume of box3 is:" << endl << Box3.volume() << endl << endl;
system("pause");
return 0;
}