[C++] A simple implementation of the cube class, which contains some member functions and global functions to calculate the surface area and volume of the cube and determine whether two cube objects are equal.

This code is a simple implementation of the cube class, which contains some member functions and global functions to calculate the surface area and volume of the cube and determine whether two cube objects are equal.

 

The code comments are as follows:

This code defines a Cubeclass to represent the cube, and contains some member functions and global functions to realize related functions. In the function, two cube objects and mainare first created , and then initialized by setting the length, width, and height of each object. Next, use member functions and global functions respectively to determine whether two cube objects are equal, and output the calculated surface area and volume.c1c2

Note: system("pause")It is used to pause the console window after the program runs to view the output. This line of code may need to be adjusted or deleted according to the actual situation in different compilation environments.

#include<iostream>
using namespace std;

class Cube
{
public:
	// 设置立方体的长度
	void setl(int l)
	{
		C_L = l;
	}

	// 获取立方体的长度
	int getl()
	{
		return C_L;
	}

	// 设置立方体的宽度
	void setw(int w)
	{
		C_W = w;
	}

	// 获取立方体的宽度
	int getw()
	{
		return C_W;
	}

	// 设置立方体的高度
	void seth(int h)
	{
		C_H = h;
	}

	// 获取立方体的高度
	int geth()
	{
		return C_H;
	}
	
	// 计算立方体的表面积
	int calculateS()
	{
		return 2 * C_L * C_W + 2 * C_L * C_H + 2 * C_W * C_H;
	}

	// 计算立方体的体积
	int calculateV()
	{
		return C_L * C_W * C_H;
	}

	// 成员函数判断两个立方体对象是否相等
	bool issamebyClass(Cube& c)
	{																	
		if (C_H == c.geth() && C_L == c.getl() && C_W == c.getw())
		{
			return true;
		}
		return false;
	}

private:
	int C_L;  // 立方体的长度
	int C_W;  // 立方体的宽度
	int C_H;  // 立方体的高度
};

// 全局函数判断两个立方体对象是否相等
bool issame(Cube& c1, Cube& c2)
{
	if (c1.geth() == c2.geth() && c1.getl() == c2.getl() && c1.getw() == c2.getw())
	{
		return true;
	}
	return false;
}

int main(void)
{
	Cube c1;
	c1.seth(10);
	c1.setl(10);
	c1.setw(10);

	cout << c1.calculateS() << endl;  // 输出立方体的表面积
	cout << c1.calculateV() << endl;  // 输出立方体的体积

	Cube c2;
	c2.seth(10);
	c2.setl(10);
	c2.setw(10);

	// 判断两个立方体对象是否相等
	bool ret = issame(c1, c2);
	if (ret)
	{
		cout << "c1和c2相等" << endl;
	}
	else
	{
		cout << "c1和c2不相等" << endl;
	}

	// 使用成员函数判断两个立方体对象是否相等
	bool ret2 = c1.issamebyClass(c2); 
	if (ret2)
	{
		cout << "利用成员函数,c1和c2相等" << endl;
	}
	else
	{
		cout << "利用成员函数,c1和c2不相等" << endl;
	}

	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/dsafefvf/article/details/131561351