本文介绍了安全地覆盖C ++虚拟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类有一个虚函数,我想在一个派生类中重写该函数。有没有办法让编译器检查我在派生类中声明的函数是否真的覆盖了基类中的一个函数?我想添加一些宏或某些确保我没有意外声明一个新的函数,而不是覆盖旧的。

I have a base class with a virtual function and I want to override that function in a derived class. Is there some way to make the compiler check if the function I declared in the derived class actually overrides a function in the base class? I would like to add some macro or something that ensures that I didn't accidentally declare a new function, instead of overriding the old one.

以这个例子:

class parent {
public:
  virtual void handle_event(int something) const {
    // boring default code
  }
};

class child : public parent {
public:
  virtual void handle_event(int something) {
    // new exciting code
  }
};

int main() {
  parent *p = new child();
  p->handle_event(1);
}

这里 parent :: handle_event c $ c>,而不是 child :: handle_event(),因为孩子的方法错过了 const 因此声明一个新的方法。这也可能是在函数名称中的打字错误或参数类型中的一些细微差异。如果基类的接口发生变化,并且某些派生类没有更新以反映变化,那么也很容易发生。

Here parent::handle_event() is called instead of child::handle_event(), because the child's method misses the const declaration and therefore declares a new method. This could also be a typo in the function name or some minor difference in the parameters types. It can also easily happen if the interface of the base class changes and somewhere some derived class wasn't updated to reflect the change.

有一些方法可以避免这个问题,我可以以某种方式告诉编译器或一些其他工具来检查这对我吗?任何有帮助的编译器标志(最好是g ++)?

Is there some way to avoid this problem, can I somehow tell the compiler or some other tool to check this for me? Any helpful compiler flags (preferably for g++)? How do you avoid these problems?

推荐答案

由于g ++ 4.7它能够理解新的C ++ 11 覆盖关键字:

Since g++ 4.7 it does understand the new C++11 override keyword:

class child : public parent {
    public:
      // force handle_event to override a existing function in parent
      // error out if the function with the correct signature does not exist
      virtual void handle_event(int something) override;
};

这篇关于安全地覆盖C ++虚拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:08