设计立方体类:
1.求出立方体的体积与面积
2.分别用全局函数和成员函数判断两个立方体是否相等
代码如下:
#include <iostream>
using namespace std;
//创建一个立方体类Cube
class Cube
{
//创建私有成员变量
private:
int m_length;
int m_width;
int m_heigh;
//创建行为应该是共有类
public:
void set_cube_parameter(int length, int width, int heigh)
{
if (length <= 0 || width <= 0 || heigh <= 0)
{
if (length <= 0)
{
m_length = 0;
cout << "length 输入有误!" << endl;
}
else if (width <= 0)
{
m_width = 0;
cout << "width 输入有误!" << endl;
}
else
{
m_heigh = 0;
cout << "height 输入有误!" << endl;
}
return;
}
m_length = length;
m_width = width;
m_heigh = heigh;
}
int get_cube_length()
{
return m_length;
}
int get_cube_width()
{
return m_width;
}
int get_cube_heigh()
{
return m_heigh;
}
int get_area_cube()
{
return 2 * (m_heigh * m_length + m_heigh * m_width + m_width * m_length);
}
int get_volume_cube()
{
return m_heigh * m_length * m_width;
}
//成员函数判断两个立方体是否相等---按引用传递
void judge_equal1(Cube& anthor)
{
if ((m_length == anthor.get_cube_length()) && (m_heigh == anthor.get_cube_length()) && (m_width == anthor.get_cube_width()))
{
cout << "两者相等" << endl;
}
else
{
cout << "两者不相等" << endl;
}
}
};
//全局函数判断两个立方体是否相等
void judge_equal2(Cube& cube1, Cube& cube3)
{
//必须把成员变量设置为公有,才可以访问该成员变量
//或者设置三个获取函数,分别获取=其长宽高
if ((cube1.get_cube_length() == cube3.get_cube_length()) && (cube1.get_cube_width() == cube3.get_cube_width()) && cube1.get_cube_heigh() == cube3.get_cube_heigh())
{
cout << "两者相等" << endl;
}
else
{
cout << "两者不相等" << endl;
}
}
int main()
{
//实例化一个立方体
Cube cube1;
Cube cube2;
Cube cube3;
//通过公共接口,设置立方体的长宽高参数
cube1.set_cube_parameter(1, 2, 3);
cube2.set_cube_parameter(2, 4, 5);
cube3.set_cube_parameter(1, 2, 3);
//显示立方体cube1的面积
cout << "cube1的面积是:" << cube1.get_area_cube() << endl;
//显示立方体cube1的体积
cout << "cube1的体积是:" << cube1.get_volume_cube() << endl;
cout << "cube1的信息" << cube1.get_cube_length() << "\t" << cube1.get_cube_width() << "\t" << cube1.get_cube_heigh() << endl;
cout << "cube2的信息" << cube2.get_cube_length() << "\t" << cube2.get_cube_width() << "\t" << cube2.get_cube_heigh() << endl;
cout << "cube3的信息" << cube3.get_cube_length() << "\t" << cube3.get_cube_width() << "\t" << cube3.get_cube_heigh() << endl;
//成员函数比较两个立方体是否相等
cube1.judge_equal1(cube2);
//全局函数比较两个立方体是否相等
judge_equal2(cube1, cube3);
system("pause");
return 0;
}
以上便是全部代码,如果对您有帮助,请点个赞哦!