2、继承方式.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. //4.6.2 继承方式
  2. //继承的语法:class 子类 : 继承方式 父类
  3. //继承方式一共有三种:
  4. //?公共继承
  5. //?保护继承
  6. //?私有继承
  7. #include <iostream>
  8. class Base1
  9. {
  10. public:
  11. int m_A;
  12. protected:
  13. int m_B;
  14. private:
  15. int m_C;
  16. };
  17. class Son1 :public Base1
  18. {
  19. public:
  20. void func()
  21. {
  22. m_A = 10; //父类中的公共权限成员到子类中依然是公共权限
  23. m_A = 10; //父类中的保护权限成员到子类中依然是保护权限
  24. //m_C = 10; //父类中的私有权限成员到子类中依然是私有权限
  25. }
  26. };
  27. void test01()
  28. {
  29. Son1 s1;
  30. s1.m_A = 100;
  31. //s1.m_B = 100; //在Son1中 m_B 是保护权限 类外访问不到
  32. }
  33. //保护继承
  34. class Base2
  35. {
  36. public:
  37. int m_A;
  38. protected:
  39. int m_B;
  40. private:
  41. int m_C;
  42. };
  43. class Son2 :protected Base2
  44. {
  45. public:
  46. void func()
  47. {
  48. m_A = 100; //父类公共到子类中变成保护权限
  49. m_B = 100; //父类保护到子类中变成保护权限
  50. //m_C = 100; //子类访问不到
  51. }
  52. };
  53. void test02()
  54. {
  55. Son2 s1;
  56. //s1.m_A = 1000; //在Son2中 m_A变为保护权限 因此类外访问不到
  57. //s1.m_B = 1000; //在Son2中 m_A变为保护权限 因此类外访问不到
  58. }
  59. class Base3
  60. {
  61. public:
  62. int m_A;
  63. protected:
  64. int m_B;
  65. private:
  66. int m_C;
  67. };
  68. class Son3 :private Base3
  69. {
  70. public:
  71. void func()
  72. {
  73. m_A = 100; //父类中公共成员,子类变为私有成员
  74. m_B = 100; //父类中保护乘员,子类变为私有成员
  75. //m_C = 100; //父类中私有成员,子类访问不到
  76. }
  77. };
  78. class Grandson :public Son3
  79. {
  80. public:
  81. void func()
  82. {
  83. //m_A = 1000; //到了Son3中 m_A变为私有 即使是儿子 也是访问不到
  84. //m_B = 1000; //到了Son3中 m_B变为私有 即使是儿子 也是访问不到
  85. }
  86. };
  87. void test03()
  88. {
  89. Son3 s1;
  90. //s1.m_A = 1000; //变为私有成员 类外访问不到
  91. //s1.m_C = 1000; //变为私有成员 类外访问不到
  92. }
  93. int main()
  94. {
  95. system("pause");
  96. return 0;
  97. }