C ++中的public
, private
继承和protected
继承有什么区别? 我在SO上发现的全部问题都与特定状况有关。 安全
若是您从另外一个类公开继承,那么每一个人都知道您正在继承,而且任何人均可以经过基类指针来使用您。 函数
若是您保护性地继承您的子类,则能够多态使用您。 优化
若是您私下继承,则只有您本身才能执行父类方法。 this
这基本上象征着其他班级对您与父母班级关系的了解 spa
class A { public: int x; protected: int y; private: int z; }; class B : public A { // x is public // y is protected // z is not accessible from B }; class C : protected A { // x is protected // y is protected // z is not accessible from C }; class D : private A // 'private' is default for classes { // x is private // y is private // z is not accessible from D };
重要说明:类B,C和D都包含变量x,y和z。 这只是访问的问题。 指针
关于受保护和私有继承的用法,您能够在这里阅读。 code
公共继承为IS-A关系建模。 用 继承
class B {}; class D : public B {};
每一个D
是一个 B
ip
私有继承为IS-IMPLEMENTED-USING关系(或任何所谓的关系)建模。 用 内存
class B {}; class D : private B {};
D
不是 B
,可是每一个D
在实现中都使用B
始终能够经过使用遏制来消除私有继承:
class B {}; class D { private: B b_; };
该D
也可使用B
来实现,在这种状况下,可使用其b_
。 与继承相比,包含是类型之间的紧密耦合,所以一般应首选。 有时使用包容代替私有继承不如私有继承方便。 一般这是懒惰的la脚借口。
我认为没有人知道什么protected
继承模型。 至少我尚未看到任何使人信服的解释。
限制继承的可见性将使代码没法看到某个类继承了另外一个类:从派生到基础的隐式转换将不起做用,从基类到派生的static_cast
也将不起做用。
只有类的成员/朋友能够看到私有继承,只有成员/朋友和派生类能够看到受保护的继承。
公共继承
IS-A继承。 按钮是一个窗口,在须要窗口的任何地方,也能够传递按钮。
class button : public window { };
受保护的继承
受保护的术语实施。 不多有用。 在boost::compressed_pair
使用,以从空类派生并使用空基类优化节省内存(下面的示例不使用模板保持原状):
struct empty_pair_impl : protected empty_class_1 { non_empty_class_2 second; }; struct pair : private empty_pair_impl { non_empty_class_2 &second() { return this->second; } empty_class_1 &first() { return *this; // notice we return *this! } };
私人继承
以术语实施。 基类的用法仅用于实现派生类。 对于特征和大小重要的状况颇有用(仅包含函数的空特征将利用空的基类优化)。 不过,一般围堵是更好的解决方案。 字符串的大小很关键,所以在这里很常见
template<typename StorageModel> struct string : private StorageModel { public: void realloc() { // uses inherited function StorageModel::realloc(); } };
公众成员
骨料
class pair { public: First first; Second second; };
存取器
class window { public: int getWidth() const; };
受保护的成员
为派生类提供加强的访问权限
class stack { protected: vector<element> c; }; class window { protected: void registerClass(window_descriptor w); };
私人会员
保留实施细节
class window { private: int width; };
请注意,C样式强制转换容许以定义的安全方式将派生类强制转换为受保护的基类或私有基类,而且也能够强制转换为另外一个方向。 应不惜一切代价避免这种状况,由于它可使代码依赖于实现细节-可是,若有必要,您可使用此技术。
基类的私有成员只能由该基类的成员访问。
该基类的成员,其派生类的成员以及在该基类和派生类以外的成员均可以访问该基类的公共成员。
基类的成员及其派生类的成员均可以访问基类的受保护成员。
私人的 :基地
保护 :基本+派生
公开 :基础+派生+任何其余成员