题解 | #设计立方体类#

设计立方体类

https://www.nowcoder.com/practice/0f02d35dcd564f0a87865d604eccbe18

题目要求:

采用封装的思想设计一个立方体类(Cube),成员变量有:长(length)、宽(width)、高(height),都为 int 类型;

成员方法有:获取表面积的方法(getArea)、获取体积的方法(getVolume)。

解题:

根据题目要求需要在cube类里实现立方体的求表面积和求体积。

首先我们要先在类里的私有成员private里定义length、width、height。

接下来在公有成员里定义获取length、width、haight的set函数,定义后再实现返回length、width、haight、area、volume的get函数

这里还有个小细节就是长方体和正方体的求表面积的公式是不一样的,我们可以在getArea里用if函数来判断不同的求表面积算法。

实现代码如下

#include <iostream>
using namespace std;

class Cube {

    // write your code here......
private:
    int length;
    int width;
    int height;
public:
    void setLength(int L)  //这里的this是一种特殊指针,它指向当前对象的地址,例如把L的值给lenght
    {
        this->length = L;
    }
    void setWidth(int W)
    {
        this->width = W;
    }
    void setHeight(int H)
    {
        this->height = H;
    }
    int getLength() {return length;}; 
    int getWidth() { return width; };
    int getHeight() { return height; };
    int getArea();   \\这里是先定义好函数,实现函数在类外实现。
    int getVolume();
};

int Cube::getArea()
{
    int Area;
    if (length == width == height)  \\这里用if函数实现长方体和正方体的不同算法
    {

        Area = length * length * 6;
    }
    else {
        Area = (length * width + width * height + length * height) * 2;
    }
    return Area;
}
int Cube::getVolume()
{
    int Volume;
    Volume = length * width * height;
    return Volume;
}
int main() {

    int length, width, height;
    cin >> length;
    cin >> width;
    cin >> height;

    Cube c;
    c.setLength(length);
    c.setWidth(width);
    c.setHeight(height);

    cout << c.getLength() << " "
        << c.getWidth() << " "
        << c.getHeight() << " "
        << c.getArea() << " "
        << c.getVolume() << endl;

    return 0;
}

#c++#
c++知识分享 文章被收录于专栏

本专栏为C++的一些知识见得。

全部评论

相关推荐

05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

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