简体   繁体   English

纯虚拟和覆盖功能(c ++)

[英]Pure virtual and override function (c++)

I looked over the internet for an answer to my questions but couldn't find any, so here I am. 我查看了互联网上的问题,但找不到任何答案,所以我在这里。

Is it correct to specify override to my function that derived from a pure virtual: 指定从纯虚拟派生的函数的覆盖是否正确:

class baseClass
{
    public:
        virtual void myFunction() = 0;
}

class derivedClass : public baseClass
{
    public:
        virtual void myFunction() override;
}

Is this correct? 它是否正确?

And my second question is: Do I have to specify virtual in the derivedClass for my function even though no class will inherite from my derived class (it will be final)? 我的第二个问题是:我是否必须在derivedClass中为我的函数指定virtual,即使没有类将从我的派生类继承(它将是最终的)?

Thank you a lot for your answers! 非常感谢您的回答!

Is this correct? 它是否正确?

Yes. 是。 Override ensures that the function is virtual and overriding a virtual function from the base class. 覆盖确保该函数是虚拟的,并覆盖基类中的虚函数。 The program is ill-formed (a compile-time error is generated) if this is not true. 如果不是这样,程序格式不正确(生成编译时错误)。

Do I have to specify virtual in the derivedClass for my function even though no class will inherite from my derived class (it will be final)? 我是否必须在我的函数的derivedClass中指定virtual,即使没有类将从我的派生类继承(它将是最终的)?

No you don't. 不,你没有。 But even if you leave away the virtual specifier it remains virtual. 但即使你放弃虚拟说明符,它仍然是虚拟的。 Because it has been declared virtual in your BaseClass . 因为它已在您的BaseClass声明为虚拟。

If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same 如果某个成员函数vf在类Base中被声明为virtual,并且某个类Derived(直接或间接地从Base派生)具有成员函数的声明,该类具有相同的成员函数

  • name 名称
  • parameter type list (but not the return type) 参数类型列表(但不是返回类型)
  • cv-qualifiers CV-预选赛
  • ref-qualifiers REF-预选赛

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration). 然后,Derived类中的此函数也是虚拟的(无论关键字virtual是否在其声明中使用)并覆盖Base :: vf(无论是否在其声明中使用了字覆盖)。 Base::vf does not need to be visible (can be declared private, or inherited using private inheritance) to be overridden. Base :: vf不需要被覆盖(可以声明为private,或使用私有继承继承)。

另外,请记住,您应该在baseClass中定义一个虚拟析构函数(可以是空的析构函数),以保证派生类中的正确资源释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM