【问题标题】:Calling base class virtual method by derived class virtual method派生类虚方法调用基类虚方法
【发布时间】:2011-10-04 06:44:49
【问题描述】:

在 C++ 中 - 假设派生类从基类派生,并且派生类覆盖的基类中有一个虚方法。有人能告诉我一个真实的场景,其中虚函数的派生类版本可能需要调用虚函数的基类版本吗?

例子,

class Base
{
public:
    Base() {}
    virtual ~Base() {}
    virtual void display() { cout << "Base version" << endl; }
};

class Derived : public Base
{
public:
    Derived() {}
    virtual ~Derived() {}
    void display();
};

void Derived::display()
{
    Base::display();  // a scenario which would require to call like this?
    cout << "Derived version" << endl;
}

【问题讨论】:

标签: c++


【解决方案1】:

每当您还需要基类行为但不想(或不能)重新实现它时,您都会这样做。

一个常见的例子是序列化:

void Derived::Serialize( Container& where )
{
    Base::Serialize( where );
    // now serialize Derived fields

}

你不关心基类是如何序列化的,但你肯定希望它序列化(否则你会丢失一些数据),所以你调用基类方法。

【讨论】:

    【解决方案2】:

    您可以在 MFC 中找到许多现实生活中的示例。 为了。例如

    CSomeDialog::OnInitDialog()
    {
      CDialogEx::OnInitDialog(); //The base class function is called.
      ----
      ----- 
    }
    

    【讨论】:

      【解决方案3】:

      是的,有时这是在序列化中完成的:

      class A{
         int x;
      public:
         A () : x(0) {}
         virtual void out( Output* o ) {
            o->write(x);
         }
         virtual void in( Input* i ) {
            i->read(&x);
         }
      }
      
      class B : public A{
         int y;
      public:
         B () : y(0) {}
         virtual void out( Output* o ) {
            A::out(o);
            o->write(y);
         }
         virtual void in( Input* i ) {
            A::in(i);
            i->read(&y);
         }
      }
      

      这样做是因为您想同时为父类和派生类读取/写入数据。

      这是一个真实的例子,说明派生类何时还必须调用基类功能并为其添加更多功能。

      【讨论】:

        【解决方案4】:

        在 GoF 状态模式的实现中,当子状态具有 exit() 函数并且超状态也具有时。你需要先执行子状态exit(),然后是超状态的

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-21
          • 2016-07-12
          • 1970-01-01
          • 1970-01-01
          • 2011-01-05
          • 2019-02-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多