虚拟?覆盖?或两者? C ++ [英] virtual? override? or both? C++

查看:84
本文介绍了虚拟?覆盖?或两者? C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几周里,有些事情困扰着我关于虚拟和替代的知识。
我了解到,当您使用虚拟函数进行继承时,必须添加 virtual 以便让编译器知道搜索正确的函数。
之后,我还了解到,在c ++ 11中,有一个新关键字-override。现在我有些困惑; 我需要在程序中同时使用虚拟关键字和替代关键字,还是最好只使用其中一个?

in the last weeks something is bugging my brain about virtual and override. I've learned that when you do inheritance with virtual function you have to add virtual to let the compiler know to search for the right function. Afterwards I learned also that in c++ 11 there is a new keyword - override. Now I'm a little confused; Do i need to use both virtual and override keywords in my program, or it's better to use only one of them?

要自我解释-我的意思的代码示例:

To explain myself - code examples of what i mean:

class Base
{
public:
    virtual void print() const = 0;
    virtual void printthat() const = 0;
    virtual void printit() const = 0;
};

class inhert : public Base
{
public:
    // only virtual keyword for overriding.
    virtual void print() const {}

    // only override keyword for overriding.
    void printthat() const override {}

    // using both virtual and override keywords for overriding.
    virtual void printit() const override {}
};

最好的方法是什么?

推荐答案

从技术上讲,您无需重写 virtual override

When you override a function you don't technically need to write either virtual or override.

原始基类声明需要关键字 virtual 将其标记为虚拟。

The original base class declaration needs the keyword virtual to mark it as virtual.

在派生类中,该函数是虚拟的,其类型与基类函数相同。

In the derived class the function is virtual by way of having the ¹same type as the base class function.

但是, override 可以通过在预期的替代不是技术上的替代时产生编译错误来帮助避免错误。例如,函数类型与基类函数不完全相同。或者是对基类的维护会更改该函数的类型,例如添加一个默认参数。

However, an override can help avoid bugs by producing a compilation error when the intended override isn't technically an override. For instance, the function type isn't exactly like the base class function. Or that a maintenance of the base class changes that function's type, e.g. adding a defaulted argument.

以同样的方式,派生类中的 virtual 关键字可能会导致此类错误通过确保该函数在进一步派生的类中仍然是虚拟的,可以使操作更加微妙。

In the same way, a virtual keyword in the derived class can make such a bug more subtle by ensuring that the function is still virtual in the further derived classes.

因此,一般建议是,


  • 使用 virtual 进行基类函数声明。

    这在技术上是必需的。

  • Use virtual for the base class function declaration.
    This is technically necessary.

override (仅)用于派生类的替代。

这有助于维护。

Use override (only) for a derived class' override.
This helps maintenance.

示例:

struct Base { virtual void foo() {} };
struct Derived: Base { void foo() override {} };


注意:

¹C ++支持协变原始指针和原始引用结果。使用协方差时,替代类型并不完全相同。它只是具有兼容的类型。

这篇关于虚拟?覆盖?或两者? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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