本文介绍了C++中的私有虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中将私有方法设为虚拟有什么好处?

What is the advantage of making a private method virtual in C++?

我在一个开源 C++ 项目中注意到了这一点:

I have noticed this in an open source C++ project:

class HTMLDocument : public Document, public CachedResourceClient {
private:
    virtual bool childAllowed(Node*);
    virtual PassRefPtr<Element> createElement(const AtomicString& tagName, ExceptionCode&);
};

推荐答案

Herb Sutter 已经很好地解释了它 这里.

Herb Sutter has very nicely explained it here.

准则 #2:最好将虚拟函数设为私有.

这让派生类重写函数来自定义根据需要进行行为,而无需进一步暴露虚函数直接通过使它们可由派生类调用(如如果功能刚刚受到保护,则可能).重点是存在虚拟功能以允许定制;除非他们也需要要直接从派生类的代码中调用,没有需要将它们设为私有

This lets the derived classes override the function to customize thebehavior as needed, without further exposing the virtual functionsdirectly by making them callable by derived classes (as would bepossible if the functions were just protected). The point is thatvirtual functions exist to allow customization; unless they also needto be invoked directly from within derived classes' code, there's noneed to ever make them anything but private

这篇关于C++中的私有虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 03:31