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

相关推荐
xiaolang_8616_wjl4 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
夜月yeyue4 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
无小道4 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++
FirstFrost --sy6 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Tanecious.7 小时前
C++--map和set的使用
开发语言·c++
Yingye Zhu(HPXXZYY)7 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle8 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
无聊的小坏坏8 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
山河木马8 小时前
前端学习C++之:.h(.hpp)与.cpp文件
前端·javascript·c++
2401_891957318 小时前
list的一些特性(C++)
开发语言·c++