zoukankan      html  css  js  c++  java
  • Effective C++ 笔记 —— Item 32: Make sure public inheritance models "is-a."

    Consider this code:

    class Rectangle 
    {
    public:
        virtual void setHeight(int newHeight);
        virtual void setWidth(int newWidth);
        virtual int height() const; // return current values
        virtual int width() const;
        // ...
    };
    
    void makeBigger(Rectangle& r) // function to increase r’s area
    {
        int oldHeight = r.height();
        r.setWidth(r.width() + 10); // add 10 to r's width
        assert(r.height() == oldHeight); // assert that r's height is unchanged
    }

    Clearly, the assertion should never fail. makeBigger only changes r's width. Its height is never modified. Now consider this code, which uses public inheritance to allow squares to be treated like rectangles:

    class Square: public Rectangle { /*...*/ };
    Square s;
    // ...
    
    assert(s.width() == s.height()); // this must be true for all squares by inheritance, s is-a Rectangle, so we can increase its area
    
    makeBigger(s); 
    
    assert(s.width() == s.height()); // this must still be true for all squares

    It's just as clear that this second assertion should also never fail. By definition, the width of a square is the same as its height. But now we have a problem. How can we reconcile the following assertions?

    • Before calling makeBigger, s's height is the same as its width;
    • Inside makeBigger, s's width is changed, but its height is not;
    • After returning from makeBigger, s’s height is again the same as its width. (Note that s is passed to makeBigger by reference, so makeBigger modifies s itself, not a copy of s.)

    public inheritance asserts that everything that applies to base class objects — everything! — also applies to derived class objects.

    Things to Remember:

    • Public inheritance means ”is-a.“ Everything that applies to base classes must also apply to derived classes, because every derived class object is a base class object.
  • 相关阅读:
    状态码
    移动端 head 中 meta 标签扫盲
    gulp 入门教程
    PHP手册-语言参考-类型-Float 浮点型
    PHP手册-语言参考-类型-Integer 整型
    PHP手册-语言参考-类型-Boolean 布尔类型
    PHP手册-语言参考-类型-简介
    模型评估与选择
    混淆矩阵与二分类评价指标
    Git 设置代理和取消设置代理
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15261431.html
Copyright © 2011-2022 走看看