前言
这篇文章主要讲述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.代码可以直接运行,如有不懂请留言哦。