zoukankan      html  css  js  c++  java
  • C++中的继承和组合区别使用

    C++的“继承”特性可以提高程序的可复用性。正因为“继承”太有用、太容易用,才要防止乱用“继承”。我们要给“继承”立一些使用规则:

      一、如果类A 和类B 毫不相关,不可以为了使B 的功能更多些而让B 继承A 的功能

      不要觉得“不吃白不吃”,让一个好端端的健壮青年无缘无故地吃人参补身体。

      二、如果类B 有必要使用A 的功能,则要分两种情况考虑:

    (1)若在逻辑上B 是A 的“一种”(a kind of ),则允许B 继承A 的功能。如男人(Man)是人(Human)的一种,男孩(Boy)是男人的一种。那么类Man 可以从类Human 派生,类Boy 可以从类Man 派生。示例程序如下:

    class Human
    {
      …
    };
    class Man : public Human
    {
      …
    };
    class Boy : public Man
    {
      …
    };

    (2)若在逻辑上A 是B 的“一部分”(a part of),则不允许B 继承A 的功能,而是要用A和其它东西组合出B。例如眼(Eye)、鼻(Nose)、口(Mouth)、耳(Ear)是头(Head)的一部分,所以类Head 应该由类Eye、Nose、Mouth、Ear 组合而成,不是派生而成。示例程序如下:

    class Eye
    {
    public:
      void Look(void);
    };
    class Nose
    {
    public:
      void Smell(void);
    };
    class Mouth
    {
    public:
      void Eat(void);
    };
    class Ear
    {
    public:
      void Listen(void);
    };
    // 正确的设计,冗长的程序
    class Head
    {
    public:
      void Look(void) { m_eye.Look(); }
      void Smell(void) { m_nose.Smell(); }
      void Eat(void) { m_mouth.Eat(); }
      void Listen(void) { m_ear.Listen(); }
    private:
      Eye m_eye;
      Nose m_nose;
      Mouth m_mouth;
    Ear m_ear;
    };

      如果允许Head 从Eye、Nose、Mouth、Ear 派生而成,那么Head 将自动具有Look、Smell、Eat、Listen 这些功能:

    // 错误的设计
    class Head : public Eye, public Nose, public Mouth, public Ear
    {
    };

    上述程序十分简短并且运行正确,但是这种设计却是错误的。这就开头所说的很多程序员经不起“继承”的诱惑而犯下设计错误。

     

    一只公鸡使劲地追打一只刚下了蛋的母鸡,你知道为什么吗?

    因为母鸡下了鸭蛋。

  • 相关阅读:
    上经 -- 乾【卦一】乾为天(三)
    上经 -- 乾【卦一】乾为天(一)
    8. Shell 文件包含
    7. Shell 函数
    6. Shell 流程控制
    5. test命令
    4. printf 命令
    3. Shell 基本运算符
    2. Shell 传递参数
    shell介绍
  • 原文地址:https://www.cnblogs.com/BeyondAnyTime/p/2510770.html
Copyright © 2011-2022 走看看