理解成员函数和全原函数的区别
案例描述:设计立方体类(Cube)
求出立方体的面积和体积
分别用全局函数和成员函数判断两个立方体是否相等。
注意事项这个立方体相等并非在空间坐标系严格相等,我们把他当做现实中的一个物体,如果把这个立方体推倒,那么他的长宽高会有改变,所以我们不能只判断长宽高分别相等的立方体为同一个立方体,那样太狭隘了,要判断六次
#include运行结果:using namespace std; class Cube { public: //设置长宽高的set,get void setLength(int l) { m_Length = l; } int getLength() { return m_Length; } void setWidth(int w) { m_Width = w; } int getWidth() { return m_Width; } void setHeight(int h) { m_Height = h; } int getHeight() { return m_Height; } //面积 int cubeS() { return 2 * (m_Length * m_Height + m_Width * m_Height + m_Length * m_Width); } //体积 int cubeV() { return m_Length * m_Width * m_Height; } bool isSameClass(Cube& c2) { if (m_Length == c2.getLength() && m_Width == c2.getWidth() && m_Height == c2.getHeight()) { return true; } else if (m_Length == c2.getLength() && m_Width == c2.getHeight() && m_Height == c2.getWidth()) { return true; } else if (m_Length == c2.getHeight() && m_Width == c2.getWidth() && m_Height == c2.getLength()) { return true; } else if (m_Length == c2.getHeight() && m_Width == c2.getLength() && m_Height == c2.getWidth()) { return true; } else if (m_Length == c2.getWidth() && m_Width == c2.getHeight() && m_Height == c2.getLength()) { return true; } else if (m_Length == c2.getWidth() && m_Width == c2.getLength() && m_Height == c2.getHeight()) { return true; } else { return false; } } private: int m_Length; int m_Width; int m_Height; }; bool isSame(Cube& c1 ,Cube& c2) { if (c1.getLength() == c2.getLength() && c1.getWidth() == c2.getWidth() && c1.getHeight() == c2.getHeight()) { return true; } else if (c1.getLength() == c2.getLength() && c1.getWidth() == c2.getHeight() && c1.getHeight() == c2.getWidth()) { return true; } else if (c1.getLength() == c2.getHeight() && c1.getWidth() == c2.getWidth() && c1.getHeight() == c2.getLength()) { return true; } else if (c1.getLength() == c2.getHeight() && c1.getWidth() == c2.getLength() && c1.getHeight() == c2.getWidth()) { return true; } else if (c1.getLength() == c2.getWidth() && c1.getWidth() == c2.getHeight() && c1.getHeight() == c2.getLength()) { return true; } else if (c1.getLength() == c2.getWidth() && c1.getWidth() == c2.getLength() && c1.getHeight() == c2.getHeight()) { return true; } else { return false; } } int main() { Cube c1; c1.setLength(5); c1.setWidth(3); c1.setHeight(4); cout << "c1的面积为:" << c1.cubeS() << endl; cout << "c1的体积为:" << c1.cubeV() << endl; Cube c2; c2.setLength(3); c2.setWidth(6); c2.setHeight(5); cout << "c2的面积为:" << c2.cubeS() << endl; cout << "c2的体积为:" << c2.cubeV() << endl; bool res = isSame(c1, c2); if (res) { cout << "这是两个相等的立方体(通过全局函数判断)" << endl; } else { cout << "这两个立方体并不相等(通过全局函数判断)" << endl; } bool res1 = c1.isSameClass(c2); if (res1) { cout << "这是两个相等的立方体(通过成员函数判断)" << endl; } else { cout << "这两个立方体并不相等(通过成员函数判断)" << endl; } system("pause"); return 0; }



