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类和层次结构中所有的子类也可以访问这些符号

相关推荐
QuantumStack1 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6731 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
whoarethenext1 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
Jay_5152 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
xiaolang_8616_wjl3 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
FrostedLotus·霜莲3 小时前
C++主流编辑器特点比较
开发语言·c++·编辑器
liulilittle8 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
十年编程老舅9 小时前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性
小刘同学32110 小时前
C++11 特性
c++·c11新特性