我在 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 {}
更清晰。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.