<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

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

          de7d5eb61bb92f324efe4fbb5ab46d8c.webp

          I.25: Prefer abstract classes as interfaces to class hierarchies(在類體系中將抽象類定義為接口會更好

          譯者注:

          1. 抽象類:不能直接生成示例的基類。

          2. 接口:不包含數(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;    vector outline;    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 functions    virtual 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ù)成員了。


          瀏覽 99
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美激情精品成人 | 国产精品嫩草影院 | 诱惑无码一区二区三区 | 亚洲成人黄色电影 | 欧美十八禁网站 |