|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 一叶枫残 于 2021-2-18 18:47 编辑
访问控制
三者访问级别:
public:任何代码
protected:这个类本身和它的子类
private:只有这个类本身
访问级别的结束标志是:遇到下一个访问级别 或 到达类的末尾
- #include <iostream>
- #include<string>
- class Computer
- {
- public:
- int a;
- Computer(int num);
- protected:
- int b;
- private:
- int c;
- };
- Computer::Computer(int num)
- {
- a = num;
- b = num+10;
- c = num+20;
- }
- int main()
- {
- Computer mycomputer(10);
- std::cout << mycomputer.a;
- std::cout << mycomputer.b;
- std::cout << mycomputer.c;
- return 0;
- }
复制代码
编译后会报错(dev_c++),主要报错信息为[Error] 'int Computer::b' is protected 与[Error] 'int Computer::c' is private
但是我们可以在类里的public创建一个函数来输出它们
- #include <iostream>
- #include<string>
- class Computer
- {
- public:
- int a;
- Computer(int num);
- void cout_abc();
- protected:
- int b;
- private:
- int c;
- };
- Computer::Computer(int num)
- {
- a = num;
- b = num+10;
- c = num+20;
- }
- void Computer::cout_abc()
- {
- std::cout << a << "\n";
- std::cout << b << "\n";
- std::cout << c << "\n";
- }
- int main()
- {
- Computer mycomputer(10);
- mycomputer.cout_abc();
- return 0;
- }
复制代码
对于private与protected,也是同样的道理。
|
|