C++学习日志13--类的应用-设计一个立方体

前言

这篇文章主要讲述C++中如何利用类设计一个立方体

一、代码

//跟着视频学习的代码,分享记录一下
#include<iostream>
#include<string>
using namespace std;
//立方体类设计
//1.创建立方体类
//2.设计属性
//3.设计行为 获取立方体的面积和体积
//4.分别利用全局函数和成员函数 判断两个立方体是否相等
class Cube
{

public:
	//设置长度
	void set_length(int length)
	{
		m_length = length;
	}
	//获取长度
	int get_length()
	{
		return m_length;
	}
	//设置宽度
	void set_width(int width)
	{
		m_width = width;
	}
	//获取宽度
	int get_width()
	{
		return m_width;
	}
	//设置高度
	void set_height(int height)
	{
		m_height = height;
	}
	//获取高度
	int get_height()
	{
		return m_height;
	}
	//获取立方体面积
	int calculate_S()
	{
		return 2 * m_length*m_width + 2 * m_length*m_height + 2 * m_width*m_height;
	
	}
	//获取立方体体积
	int get_V()
	{
	
		return m_length*m_width*m_height;
	}
	//用成员函数判断两个立方体是否相等
	bool isSameByClass(Cube &c)
	{
		if (m_height == c.get_height()
			&& m_length == c.get_length()
			&& m_width == c.get_width()
			)
			return true;
		return false;
	
	
	}
private:
	int m_length;
	int m_width;
	int m_height;


};
//利用全局函数判断 两个立方体是否相等
bool isSame(Cube &c1, Cube &c2)
{
	if (c1.get_height() == c2.get_height()
		&& c1.get_length() == c2.get_length()
		&& c1.get_width() == c2.get_width()
		)
		return true;
	return false;


}
int main()
{    
	Cube c1;
	c1.set_height(10);
	c1.set_length(10);
	c1.set_width(10);
	cout << "c1的面积为  " << c1.calculate_S() << endl;
	cout << "c1的体积为:   " << c1.get_V() << endl;
	Cube c2;
	c2.set_height(10);
	c2.set_length(10);
	c2.set_width(10);

	//利用全局函数判断
	bool ret = isSame(c1, c2);
	if (ret)
	{

		cout << "相等" << endl;
	}
	else
	{
		cout << "不相等" << endl;
	}
	//利用成员函数判断
	ret = c1.isSameByClass(c2);
		if (ret)
		{

			cout << "相等" << endl;
		}
		else
		{
			cout << "不相等" << endl;
		}
	system("pause");
}

总结

1.代码可以直接运行,如有不懂请留言哦。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@白圭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值