C++的可见性

时间:2024-04-15 18:55:44

可见性定义

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

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

代码案例: 

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的意思是友元,实际上可以从类中访问私有成员

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

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