2011-10-04 92 views
4

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

任何情况下,派生类都在扩展基类的功能,所以不是重复基类的功能,而是调用它,然后执行其他步骤在派生类中。 – Praetorian

回答

11

你每次都需要基类行为但不希望(或不能)重新实现它。

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

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

} 

你不在乎类如何基地是系列化的,但你肯定希望它序列化(否则你失去了一些数据),所以你调用基类的方法。

3

你可以找到很多的MFC现实生活中的例子。 。 e.g

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

,因为你要既为父类以及为您的派生类的读/写数据时完成。

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

0

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