您是否应该使用受保护的成员变量? [英] Should you ever use protected member variables?

查看:80
本文介绍了您是否应该使用受保护的成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您应该使用受保护的成员变量吗?优点是什么,这会导致什么问题?

Should you ever use protected member variables? What are the the advantages and what issues can this cause?

推荐答案

您应该使用受保护的成员变量吗?

Should you ever use protected member variables?

取决于您对隐藏状态的挑剔程度.

Depends on how picky you are about hiding state.

  • 如果您不希望任何内部状态泄漏,那么将所有成员变量都声明为私有是可行的方法.
  • 如果您不太在乎子类可以访问内部状态,那么受保护就足够了.

如果开发人员出现并为您的类提供子类,则他们可能会弄乱它,因为他们无法完全理解它.对于私有成员,除了公共接口之外,他们看不到具体的实现细节,这使您以后可以灵活地进行更改.

If a developer comes along and subclasses your class they may mess it up because they don't understand it fully. With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later.

这篇关于您是否应该使用受保护的成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆