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

相关推荐
blasit9 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马5 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法