需要重写的虚函数调用基类实现 [英] Requiring overridden virtual functions to call base implementations

查看:141
本文介绍了需要重写的虚函数调用基类实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++类层次结构中,是否有可能强制要求某个特定的虚函数总是调用其基类的实现? (类似于构造函数链?)

Within a C++ class hierarchy, is it possible to enforce a requirement that a particular virtual function always call its base class's implementation also? (Like the way constructors chain?)

我在看一个深层类层次结构有一些公共接口函数的情况,每个子层覆盖。我想让每个派生类重写链接到基类。使用例如下面的代码显式地做到这一点很简单,但是有人实现一个新的派生类可能会忘记链接到基础。

I'm looking at a case where a deep class hierarchy has some common interface functions which each child overrides. I'd like each derived class' override to chain through to the base class. It's straightforward to do this explicitly with eg the code below, but there's the risk that someone implementing a new derived class might forget to chain through to the base.

是否有一些模式来强制执行此操作,如果覆盖未能链接基础,编译器将抛出一个错误?

Is there some pattern to enforce this, such that the compiler will throw an error if an override fails to chain the base?

>

So, in

class CAA 
{
   virtual void OnEvent( CEvent *e ) { 
     // do base implementation stuff;
   }
}

class CBB : public CAA
{
   typedef CAA BaseClass;
   virtual void OnEvent( CEvent *e ) { 
       DoCustomCBBStuff();
       BaseClass::OnEvent( e ); // chain to base
   }
}

class CCC : public CBB
{
   typedef CBB BaseClass;
   virtual void OnEvent( CEvent *e ) { 
       Frobble();
       Glorp();
       BaseClass::OnEvent( e ); // chain to CBB which chains to CAA, etc
   }
}

class CDD : public CCC
{
   typedef CCC BaseClass;
   virtual void OnEvent( CEvent *e ) { 
       Meep();
       // oops! forgot to chain to base!
   }
}

是有办法的,有些模板技巧或句法g头,使CDD抛出一个更明显的错误?

is there a way, some template trick or syntactic gimmick, to make CDD throw a more obvious error?

推荐答案

它的方法是基类方法不是虚拟的,受保护的虚方法。

The way its done is the base class method is not virtual and calls a protected virtual method.

当然,只处理一个级别。

Of course, that only handles one level.

典型的回复是添加评论

// Always call base class method

这篇关于需要重写的虚函数调用基类实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆