【C++之基于对象】计算3个长方柱的体积

题目要求

需要求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类
************************************************************************
*/

#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()
************************************************************************
*/

#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:   主函数
************************************************************************
*/

#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;
}

运行结果

运行结果

#C/C++##c++#
C++学习 文章被收录于专栏

c++面向对象程序设计课, 作业题选自谭浩强的《c++面向对象程序设计》(第2版)

全部评论
计算3个长方柱的体积
点赞 回复 分享
发布于 2022-08-28 13:47 河南

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务