C++(14th for two):public,protected and private
本帖最后由 一叶枫残 于 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++),主要报错信息为 'int Computer::b' is protected 与 '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,也是同样的道理。
页:
[1]