经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C » 查看文章
C++基础 C++对类的管理——封装
来源:cnblogs  作者:还想抢救抢救  时间:2018/10/16 9:36:12  对本文有异议

1.封装

  两层含义:

  (1)把事物的属性和方法结合成个整体。

  (2)对类的属性和方法进行访问控制,对不信的进行信息屏蔽。

2.访问控制

  控制分为 类的内部,类的外部。

  public 修饰的成员,可在内部和外部访问。

  private 修饰的成员,只能在内部访问。

  封装就像一个手表,里面有很复杂的功能,但输出只有表盘,输入只能转转轴。

3. 类与对象

  抽象一个类,用类去定义对象。

  类是数据类型,是抽象的,对象是具体的变量,占用内存空间。

4. struct 和 class 关键字的区别

  在 struct 定义的类中,所有成员的默认访问控制为 public

  在 class 中 为 private。

5. 练习

(1)设计立方体类(cube),求出立方体的面积和体积,求两个立方体,是否相等。

  1. #include <iostream>
  2. using namespace std;
  3. class cube{
  4. private:
  5. double length;
  6. double high;
  7. double width;
  8. public:
  9. double getLength()
  10. {
  11. return length;
  12. }
  13. double getHigh()
  14. {
  15. return high;
  16. }
  17. double getWidth()
  18. {
  19. return width;
  20. }
  21. void setLength(double length)
  22. {
  23. this->length = length;
  24. }
  25. void setWidth(double width)
  26. {
  27. this->width = width;
  28. }
  29. void setHigh(double high)
  30. {
  31. this->high = high;
  32. }
  33. double getArea()
  34. {
  35. return 0;
  36. }
  37. double getVolume()
  38. {
  39. return 0;
  40. }
  41. bool isEqualCube1(class cube c);
  42. bool isEqualCube2(class cube *c);
  43. bool isEqualCube3(class cube &c);
  44. protected:
  45. };
  46. bool cube::isEqualCube1(class cube c)
  47. {
  48. /* 下面的函数调用体现出封装的强大,因为复制的参数,不仅带有属性,还有函数 */
  49. if (c.getLength() == this->length &&
  50. c.getHigh() == this->high &&
  51. c.getWidth() == this->width)
  52. return true;
  53. else
  54. return false;
  55. }
  56. bool cube::isEqualCube2(class cube *c)
  57. {
  58. if (c->getLength() == this->length &&
  59. c->getHigh() == this->high &&
  60. c->getWidth() == this->width)
  61. return true;
  62. else
  63. return false;
  64. return true;
  65. }
  66. bool cube::isEqualCube3(class cube &c)
  67. {
  68. if (c.getLength() == this->length &&
  69. c.getHigh() == this->high &&
  70. c.getWidth() == this->width)
  71. return true;
  72. else
  73. return false;
  74. }
  75. void main(void)
  76. {
  77. class cube c1, c2;
  78. c1.setHigh(1);
  79. c1.setLength(1);
  80. c1.setWidth(1);
  81. c2.setHigh(2);
  82. c2.setLength(2);
  83. c2.setWidth(2);
  84. cout << "c1's area = " << c1.getArea() << endl;;
  85. cout << "c2's volume = " << c2.getVolume() << endl;
  86. if (c1.isEqualCube1(c2))
  87. cout << "c1 == c2" << endl;
  88. else
  89. cout << "c1 != c2" << endl;
  90. system("pause");
  91. return ;
  92. }

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号