覆盖纯虚函数时使用`override`有什么意义吗? [英] Is there any point in using `override` when overriding a pure virtual function?

查看:355
本文介绍了覆盖纯虚函数时使用`override`有什么意义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

class Base {
  virtual void my_function() = 0;
};

class Derived : Base {
  void my_function() override;
};

根据我的阅读, override 关键字用来确保我们在要覆盖的函数中具有正确的签名,这似乎是它的唯一用法。

From what I read, the override keyword is used to make sure that we have the correct signature in the function that we are overriding, and it seems to be its only use.

但是,对于a纯虚函数,如果我们在Derived类(或Base类,取决于人们的看法)中使用了不正确的签名,则编译器将引发错误。那么,在 Derived :: my_function()声明的末尾添加 override 有什么意义吗?

However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class (or Base class, depending on how one see things). So, is there any point in adding override at the end of Derived::my_function() declaration?

推荐答案


但是,在纯虚拟函数的情况下,如果我们使用派生类中的签名不正确

However, in the case of a pure virtual function, the compiler would throw an error if we used an incorrect signature in the Derived class

不,这会编译:

class Base {
  virtual void my_function() = 0;
};

class Derived : Base {
  void my_function(int);
//                 ^^^ mistake!
};

虽然这不是:

class Base {
  virtual void my_function() = 0;
};

class Derived : Base {
  void my_function(int) override;
};




错误: void派生:: my_function( int)标记为覆盖,但不会覆盖



< hr>

您正在谈论的错误仅在实例化 Derived - override 可让您及早发现错误,并使 Derived 的定义更清晰/更具可读性。


The error you're talking about only occurs when instantiating Derived - override allows you to catch the mistake earlier and makes the definition of Derived clearer/more readable.

这篇关于覆盖纯虚函数时使用`override`有什么意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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