我在 Effective C++ 条款 35 里面看到这种模板模式的写法,有点困惑:
class GameCharacter {
public:
int healthValue() const {
// do something
return doHealthValue();
// do something
}
private:
virtual int doHealthValue() const = 0;
};
我从 Java 转过来,Java 里面是没有 private abstract 的,一般模板模式的写法都是 protected abstract ,因为通常来说,private 的函数就是基类内部的函数,派生类也无权知晓,也不用提 overwrite
那么,在 C++ 里面,是不是也写 protected virtual 比较好呢 ,功能上应该区别不大
stackoverflow 上也有人讨论,
有人说
Prefer to make virtual functions private.
This lets the derived classes override the function to customize the behavior as needed, without further exposing the virtual functions directly by making them callable by derived classes (as would be possible if the functions were just protected). The point is that virtual functions exist to allow customization; unless they also need to be invoked directly from within derived classes' code, there's no need to ever make them anything but private.
确实也有些道理,但是也只有在基类被直接使用的时候有用。
否则,protected: virtual int doHealthValue() const = 0 似乎比 private: virtual int doHealthValue() const {} 更清晰。