C++ 风格:为覆盖的方法添加 virtual 关键字前缀

我一直在与我的同事讨论是在重写的方法前添加 virtual 关键字,还是只在原始基类中添加前缀.

I've been having a discussion with my coworkers as to whether to prefix overridden methods with the virtual keyword, or only at the originating base class.

我倾向于在所有虚方法(即涉及虚表查找的方法)前加上 virtual 关键字.我的理由有三个:

I tend to prefix all virtual methods (that is, methods involving a vtable lookup) with the virtual keyword. My rationale is threefold:

  1. 鉴于 C++ 缺少覆盖关键字,虚拟的存在关键字至少会通知您该方法涉及查找和理论上可以被覆盖进一步的专业化,或者可能是通过指向更高的指针调用基类.

  1. Given that C++ lacks an override keyword, the presence of the virtual keyword at least notifies you that the method involves a lookup and could theoretically be overridden by further specializations, or could be called through a pointer to a higher base class.

一直使用这种风格意味着,当你看到一个方法(至少在我们的代码中)没有virtual关键字,你可以最初假设它既不是派生自基础或专业在子类中.

Consistently using this style means that, when you see a method (at least within our code) without the virtual keyword, you can initially assume that it is neither derived from a base nor specialized in subclass.

如果由于某些错误,虚拟已从 IFoo 中删除,所有孩子们仍将发挥作用(CFooSpecialization::DoBar 会仍然覆盖 CFooBase::DoBar,而不是简单地隐藏它).

If, through some error, the virtual were removed from IFoo, all children will still function (CFooSpecialization::DoBar would still override CFooBase::DoBar, rather than simply hiding it).

据我所知,反对这种做法的论点是,但那个方法不是虚拟的"(我认为这是无效的,并且是对虚拟性的误解),以及当我看到 virtual 关键字时,我预计这意味着有人从中得出结论,并去寻找他们."

The argument against the practice, as I understood it, was, "But that method isn't virtual" (which I believe is invalid, and borne from a misunderstanding of virtuality), and "When I see the virtual keyword, I expect that means someone is deriving from it, and go searching for them."

假设的类可能分布在多个文件中,并且有多个专业化.

The hypothetical classes may be spread across several files, and there are several specializations.

class IFoo {
public:
    virtual void DoBar() = 0;
    void DoBaz();
};

class CFooBase : public IFoo {
public:
    virtual void DoBar(); // Default implementation
    void DoZap();
};


class CFooSpecialization : public CFooBase {
public:
    virtual void DoBar(); // Specialized implementation
};

在风格上,您会从两个派生类中删除 virtual 关键字吗?如果是这样,为什么?Stack Overflow 的想法是什么?

Stylistically, would you remove the virtual keyword from the two derived classes? If so, why? What are Stack Overflow's thoughts here?

推荐答案

我完全同意你的理由.这是一个很好的提醒,该方法在调用时将具有动态调度语义.您同事使用的该方法不是虚拟的"论点完全是虚假的.他混淆了虚拟和纯虚拟的概念.

I completely agree with your rationale. It's a good reminder that the method will have dynamic dispatch semantics when called. The "that method isn't virtual" argument that you co-worker is using is completely bogus. He's mixed up the concepts of virtual and pure-virtual.

相关文章