1

假设我有以下课程:

class Airplane
{
    virtual bool Fly(uint64_t destinationID)
    {
        //Do what an airplane does to be flown.
    }

    /*
     *  More function and data members.
     */
}

class SomeModel: public Airplane
{
    virtual bool Fly(uint64_t destinationID);
    {
       //Do something that SomeModel specifically should do before it gets flying.  

       //Do exactly what Airplane::Fly does.
    }
}    

我的问题是如何实现 SomeModel::Fly。一种简单的方法如下:

virtual bool SomeModel::Fly(uint64_t destinationID)
{
    //Do something that SomeModel specifically should do before it gets flying.  

    Airplane::Fly(destinationID);
}

有更好的方法吗?还是有其他理由选择另一种方式。我知道这是一个普遍的问题,但这是我第一次必须实现这样的方法,所以我想确保我没有遗漏任何东西。

编辑

我觉得值得强调的是,Airplane 不是一个通用或抽象的类,公司中的许多 Airplane 只是飞机,并没有任何继承性,但有一个特定的模型,尽管它具有一些特定的行为。

4

1 回答 1

1

这实际上取决于您要实现的目标。您的示例当然是有效的,并且是一种类型问题的一种解决方案(早期需要一些设置或其他变体)。

这个主题的另一个变体是使用虚拟设置,然后使用常见的“飞行”方法。

所以:

class Airplane
{
   bool Fly(uint64_t destinationID)
   {
      SetupForFlight();
      // do actual flying stuff
      ...  
      ...
   }

   virtual void SetupForFlight() { // do nothing for standard airplane }
}

class Boeing747: public Airplane
{
    ...
    void SetupForFLight() 
    {
       ... do stuff that needs to be set up here. 
    }
    ...
}

这两种方法都有好处,并且可能取决于您要建模的内容哪个更好。

当然,你也可以AfterLanding在末尾有一个类型函数Fly

只是出于好奇,是否有这么多目的地需要为它们设置 64 位值 - 我从未真正考虑过,只是好奇。

编辑:我认为我所描述的是“模板方法模式”。我对这些东西的名字不是很好,我只知道它是如何工作的......

于 2013-05-10T11:57:02.127 回答