题目要求:
采用封装的思想设计一个立方体类(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;
}

京公网安备 11010502036488号