首页 文章

通过派生类虚方法调用基类虚方法

提问于
浏览
5

在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;
}

4 回答

  • 0

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

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

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

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

  • 3

    你可以在MFC中找到很多真实的例子 . 对于 . 例如

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

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

    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);
       }
    }
    

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

    这是一个真实的例子,关于派生类何时还必须调用基类功能以及向它添加更多内容 .

  • 3

    在GoF状态模式的实现中,当子状态具有 exit() 函数且超状态也具有时 . 您需要首先执行子状态 exit() ,然后执行超级状态

相关问题