鱼C论坛

 找回密码
 立即注册
查看: 2544|回复: 0

[技术交流] C++(14th for two):public,protected and private

[复制链接]
发表于 2021-2-18 18:43:41 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 一叶枫残 于 2021-2-18 18:47 编辑

访问控制

三者访问级别:
public:任何代码
protected:这个类本身和它的子类
private:只有这个类本身

访问级别的结束标志是:遇到下一个访问级别 或 到达类的末尾


  1. #include <iostream>
  2. #include<string>

  3. class Computer
  4. {
  5. public:
  6.         int a;
  7.         Computer(int num);
  8. protected:
  9.         int b;
  10. private:
  11.         int c;
  12. };

  13. Computer::Computer(int num)
  14. {
  15.         a = num;
  16.         b = num+10;
  17.         c = num+20;
  18. }

  19. int main()
  20. {
  21.         Computer mycomputer(10);
  22.         std::cout << mycomputer.a;
  23.         std::cout << mycomputer.b;
  24.         std::cout << mycomputer.c;      
  25.         return 0;
  26. }
复制代码

编译后会报错(dev_c++),主要报错信息为[Error] 'int Computer::b' is protected 与[Error] 'int Computer::c' is private

但是我们可以在类里的public创建一个函数来输出它们
  1. #include <iostream>
  2. #include<string>

  3. class Computer
  4. {
  5. public:
  6.         int a;
  7.         Computer(int num);
  8.         void cout_abc();
  9. protected:
  10.         int b;
  11. private:
  12.         int c;
  13. };

  14. Computer::Computer(int num)
  15. {
  16.         a = num;
  17.         b = num+10;
  18.         c = num+20;
  19. }

  20. void Computer::cout_abc()
  21. {
  22.         std::cout << a << "\n";
  23.         std::cout << b << "\n";
  24.         std::cout << c << "\n";
  25. }

  26. int main()
  27. {
  28.         Computer mycomputer(10);
  29.         mycomputer.cout_abc();  
  30.         return 0;
  31. }
复制代码
  1. 10
  2. 20
  3. 30
复制代码

对于private与protected,也是同样的道理。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-1 18:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表