C++的可见性

可见性定义

1、可见性是一个属于面向对象编程的概念,它指的是类的某些成员或方法实际上有多可见
2、可见性是指谁能看到它们,谁能调用它们,谁能使用它们
3、可见性是对程序实际运行方式完全没有影响的东西,对程序性能或类似的东西也没有影响,它纯粹是语言中存在的东西,让你写出更好的代码或者帮助你组织代码

C++中有三个基础的可见性修饰符,private、protected、public

代码案例:

cpp 复制代码
class Entity
{
private:
    int X, Y;
	void print() { }
public:
	Entity()
	{
		X = 0;
		print();
	}
};

class Player : public Entity
{
public:
	Player()
	{
		X = 2;
		print();
	}
};

int main()
{
	Entity e;
	e.X = 2; // private和protected仍然不能在main()中可见
	e.print(); // private和protected仍然不能在main()中可见,这在类外,不是Entity的子类
	cin.get();
	return 0;
}

private: 意味着只有这个Entity类可以访问这些变量,意味着它可以读取和写入它们,但是也有friend关键字,它可以让类或者函数成为类Entity的朋友(友元)。

friend的意思是友元,实际上可以从类中访问私有成员

类中默认的可见性时私有的

cpp 复制代码
class Entity
{
protected:
    int X, Y;
	void print() { }
public:
	Entity()
	{
		X = 0;
		print();
	}
};

class Player : public Entity
{
public:
	Player()
	{
		X = 2;
		print();
	}
};
int main()
{
	Entity e;
	e.X = 2; //  private和protected仍然不能在main()中可见
	e.print(); // private和protected仍然不能在main()中可见,这在类外,不是Entity的子类
	cin.get();
	return 0;
}

protected: protected比private更可见,比public更不可见

protected的意思是这个Entity类和层次结构中所有的子类也可以访问这些符号

相关推荐
lightqjx3 分钟前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
阿猿收手吧!36 分钟前
【C++】string_view:高效字符串处理指南
开发语言·c++
Word码1 小时前
[C++语法] 继承 (用法详解)
java·jvm·c++
lxl13071 小时前
C++算法(1)双指针
开发语言·c++
淀粉肠kk1 小时前
C++11列表初始化:{}的革命性进化
c++
zhooyu2 小时前
C++和OpenGL手搓3D游戏编程(20160207进展和效果)
开发语言·c++·游戏·3d·opengl
HAPPY酷2 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
茉莉玫瑰花茶3 小时前
C++ 17 详细特性解析(5)
开发语言·c++·算法
cpp_25013 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25013 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷