Bootstrap

【C++面向对象】设计立方体类

设计立方体类(Cube)
求出立方体的面积和体积
分别用全局函数和成员函数判断两个立方体是否相等。

class Cube {
public:
	void setValue(int lenght, int width, int higth) {
		m_L = lenght;
		m_W = width;
		m_H = higth;
	}

	int getL() {
		return m_L;
	}

	int getW() {
		return m_W;
	}

	int getH() {
		return m_H;
	}
	
	//面积
	int getS() {
		return 2 * m_L * m_W + 2 * m_L * m_H + 2 * m_W * m_H;
	}
	//体积
	int getV() {
		return m_L * m_W * m_H;
	}

	//判断成员函数
	bool isSame(Cube &c2) {
		if (m_L == c2.m_L && m_W == c2.m_W && m_H == c2.m_H) {
			return true;
		}
		return false;
	}

private:
	int m_L;//长
	int m_W;//宽
	int m_H;//高
};

bool isSame(Cube &c1, Cube &c2) {
	if (c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH()) {
		return true;
	}
	return false;
}

int main() {
	Cube c1;
	c1.setValue(10, 10, 10);
	cout << "立方体的面积:" << c1.getS() << endl;
	cout << "立方体的体积:" << c1.getV() << endl;

	Cube c2;
	c2.setValue(1, 2, 3);
	
	//成员函数判断
	int ret = c1.isSame(c2);
	if (ret) {
		cout << "成员函数判断c1和c2相等" << endl;
	}
	else cout << "成员函数判断c1和c2不相等" << endl;


	//全局函数判断
	if(ret=isSame(c1,c2)) {
		cout << "全局函数判断c1和c2相等" << endl;
	}
	else cout << "全局函数判断c1和c2不相等" << endl;

	return 0;
}

;