简体   繁体   English

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

[英]Calling base class virtual method by derived class virtual method

In C++ - take a case where derived class deriving from a base class and there is a virtual method in base class which the derived class is overriding. 在C ++中 - 假设派生类派生自基类,并且派生类重写的基类中有一个虚方法。 Could someone tell me a real life scenario where the derived class version of the virtual function might require to call the base class version of the virtual function? 有人能告诉我一个真实生活场景,虚拟函数的派生类版本可能需要调用虚函数的基类版本吗?

Example, 例,

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

You do that every time when you also need base class behavior but don't want (or can't) reimplement it. 每当你还需要基类行为但不想(或不能)重新实现它时,你就会这样做。

One common example is serialization: 一个常见的例子是序列化:

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

}

you don't care how base class is serialized, but you definitely want it to serialize (otherwise you lose some data), so you call the base class method. 你不关心如何序列化基类,但你肯定希望它序列化(否则你会丢失一些数据),所以你调用基类方法。

You can find lots of real-life examples in MFC. 你可以在MFC中找到很多真实的例子。 For. 对于。 eg 例如

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

Yes, sometimes this is done in serialization: 是的,有时这是在序列化中完成的:

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

This is done because you want to read/write data both for the parent class as well as for your derived class. 这样做是因为您想要为父类和派生类读取/写入数据。

This is a real-life example as to when the derived class must also call the base class functionality as well as add something more to it. 这是一个真实的例子,关于派生类何时还必须调用基类功能以及向它添加更多内容。

In an implementation of the GoF State Pattern , when a substate has an exit() function and the superstate has too. 在GoF状态模式的实现中,当子状态具有exit()函数并且超状态也具有。 You are required to execute the substate exit() first, then the superstate's 您需要首先执行子状态exit() ,然后执行超级状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM