gpt4 book ai didi

c++ - 在 C++ 中子类化时为什么有时需要向重写的函数添加 virtual 关键字?

转载 作者:行者123 更新时间:2023-12-01 08:50:02 28 4
gpt4 key购买 nike

为什么我有时在 C++ 示例中看到在谈论子类/继承时,基类有 virtual 关键字,有时重写的函数也有 virtual 关键字,为什么有时需要在子类中添加 virtual 关键字?
例如:

class Base 
{
Base(){};
virtual void f()
......
}
};

class Sub : public Base
{
Sub(){};
virtual void f()
...new impl of f() ...
}
};

最佳答案

这不是必需的,但如果您只看到派生类定义,它有助于提高可读性。

§10.3 [class.virtual]/3

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides 97) Base::vf.



其中脚注 97) 基本上说明,如果参数列表不同,该函数将不会覆盖也不一定是 virtual

关于c++ - 在 C++ 中子类化时为什么有时需要向重写的函数添加 virtual 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5309414/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com