我总是看到很多虚拟函数在头文件中被声明为 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)。
public
和 protected
继承分为两种设计模式类别:
模板函数模式:
class Base { public: void foo() { bar(); }; protected: virtual void bar() = 0; }; class Implementation : public Base { void bar() { // provide the implementation } };
界面模式:
struct Interface { virtual void foo() = 0; virtual ~Interface() {} }; class Implementation : public Interface { public: void foo() { // provide the implementation } };
还有其他设计模式,可能会完全省略 virtual
(请参阅 CTRP ),但 public
和 protected
的语义仍被保留。
关于c++ - 使用 protected 或公共(public)的虚拟函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503401/