当前位置:   article > 正文

类和对象-封装-设计案例-立方体类_设计派生类只利用直接基类立方体类的封装

设计派生类只利用直接基类立方体类的封装
  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //class代表一个类,后面紧跟类名
  5. class Cube
  6. {
  7. public:
  8. void setm_l(int l)
  9. {
  10. m_l = l;
  11. }
  12. int getm_l()
  13. {
  14. return m_l;
  15. }
  16. void setm_w(int w)
  17. {
  18. m_w = w;
  19. }
  20. int getm_w()
  21. {
  22. return m_w;
  23. }
  24. void setm_h(int h)
  25. {
  26. m_h = h;
  27. }
  28. int getm_h()
  29. {
  30. return m_h;
  31. }
  32. int getS()
  33. {
  34. return 2 * (m_l*m_w + m_l*m_h + m_w*m_h);
  35. }
  36. int getV()
  37. {
  38. return m_l*m_h*m_w;
  39. }
  40. //利用成员函数判断两个立方体是否相等
  41. bool issamebyclass(Cube &c)
  42. {
  43. if (m_h == c.getm_h() && m_l == c.getm_l() && m_w == c.getm_w())
  44. return true;
  45. return false;
  46. }
  47. private:
  48. int m_l; //
  49. int m_w; //
  50. int m_h;//
  51. };
  52. //全局函数判断两个立方体是否相等
  53. bool issame(Cube &c1, Cube &c2)
  54. {
  55. if (c1.getm_h() == c2.getm_h() && c1.getm_l() == c2.getm_l() && c1.getm_w() == c2.getm_w())
  56. return true;
  57. return false;
  58. }
  59. int main()
  60. {
  61. Cube c1;
  62. c1.setm_l(1);
  63. c1.setm_w(2);
  64. c1.setm_h(3);
  65. cout << "c1的面积为:" << c1.getS() << endl;
  66. cout << "c1的体积为:" << c1.getV() << endl;
  67. Cube c2;
  68. c2.setm_l(1);
  69. c2.setm_w(2);
  70. c2.setm_h(3);
  71. //全局函数判断是否相等
  72. bool reet = issame(c1, c2);
  73. if (reet)
  74. {
  75. cout << "c1和c2相等" << endl;
  76. }
  77. else
  78. {
  79. cout << "c1和c2不等" << endl;
  80. }
  81. Cube c3;
  82. c3.setm_l(2);
  83. c3.setm_w(2);
  84. c3.setm_h(3);
  85. //成员函数判断是否相等
  86. bool ret = c1.issamebyclass(c3);
  87. if (ret)
  88. {
  89. cout << "c1和c3相等" << endl;
  90. }
  91. else
  92. {
  93. cout << "c1和c3不等" << endl;
  94. }
  95. system("pause");
  96. return 0;
  97. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/463463
推荐阅读
相关标签
  

闽ICP备14008679号