设计立方体类

设计立方体类:

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

以上便是全部代码,如果对您有帮助,请点个赞哦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hskwcy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值