鱼C论坛

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

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

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

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

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

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;
 } 
10
20
30
对于private与protected,也是同样的道理。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-22 15:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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