C++核心準則邊譯邊學-I.25 在類體系中將抽象類定義成接口會更好

I.25: Prefer abstract classes as interfaces to class hierarchies(在類體系中將抽象類定義為接口會更好)
譯者注:
抽象類:不能直接生成示例的基類。
接口:不包含數(shù)據(jù)成員的抽象類。
Reason(原因)
Abstract classes are more likely to be stable than base classes with state.
抽象類有很大的可能比包含狀態(tài)的基類更穩(wěn)定。
譯者注:結(jié)合全文,這里的抽象類應該指接口。
Example, bad(反面示例)
You just knew that Shape would turn up somewhere :-)
你只知道Shape會在某處表示:-)
class Shape { // bad: interface class loaded with datapublic:Point center() const { return c; }virtual void draw() const;virtual void rotate(int);// ...private:Point c;vectoroutline; Color col;};
This will force every derived class to compute a center -- even if
that's non-trivial and the center is never used. Similarly, not every Shape has a Color, and many Shapes are best represented without an outline defined as a sequence of Points. Abstract classes were invented to discourage users from writing such classes:
這將強迫每個派生類都要計算中心位置-哪怕是那些特殊且中心從未不用的圖形。類似的,也不是所有的圖形都有顏色,很多圖形最好不要包含一個有Points序列定義的輪廓線。發(fā)明抽象類就是為了鼓勵用戶寫出下面的類:
class Shape { // better: Shape is a pure interfacepublic:virtual Point center() const = 0; // pure virtual functionsvirtual void draw() const = 0;virtual void rotate(int) = 0;// ...// ... no data members ...// ...virtual ~Shape() = default;};
Enforcement(實施建議)
(Simple) Warn if a pointer/reference to a class C is assigned to a pointer/reference to a base of C and the base class contains data members.
(簡單)如果指向類C的指針或引用被復制被C的基類類型的指針或引用,而且基類包含數(shù)據(jù)成員時,報警。
譯者注:也就是說,大師的意見是:基類基本上抽象類就不要有數(shù)據(jù)成員了。
