c++ - 使用 protected 或公共(public)的虚拟函数?

标签 c++ public protected

我总是看到很多虚拟函数在头文件中被声明为 protected 例子。将虚函数声明为 public 是错误的吗?使用虚拟函数的最佳实践是什么?

最佳答案

Is it wrong to declare virtual functions as public?

没有。

What is the best practice when using virtual functions?

这完全取决于您的用例。关键字本身在使用上是正交的。

有时,拥有 protected 虚拟函数(例如template design pattern)是件好事。 ,大多数情况下,虚拟函数被声明为public以提供接口(interface)。

publicprotected 继承分为两种设计模式类别:

  1. 模板函数模式:

    class Base {
    public:
        void foo() {
            bar();
        };
    protected:
        virtual void bar() = 0;
    };
    
    class Implementation : public Base {
         void bar() {
             // provide the implementation
         }
    };
    
  2. 界面模式:

    struct Interface {
        virtual void foo() = 0;
        virtual ~Interface() {}
    };
    
    class Implementation : public Interface {
    public:
         void foo() {
             // provide the implementation
         }
    };
    

还有其他设计模式,可能会完全省略 virtual (请参阅 CTRP ),但 publicprotected 的语义仍被保留。

关于c++ - 使用 protected 或公共(public)的虚拟函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503401/

相关文章:

c++ - 在 C++ 方法签名中 * 是什么意思?

java - 只能从派生类访问基类方法

java - 如何访问父类(super class)动态对象的 protected 成员变量

c++ - 基类构造函数 protected 时在派生类成员函数中创建基类实例

c++ - 非 B 树数据结构,其中昆虫以排序的方式完成,但我可以稍后从随机位置删除对象

c++ - 如何在旋转框上渲染边界框

c++ - 如何将 QAction 从 QMenu 传递到 Qt 插槽

java - 公共(public)与私有(private)

c++ - 返回对私有(private)成员与公共(public)成员的引用

ios - CoreWLAN 或适用于 IOS 7 的任何其他公共(public) API