加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

UML—里氏替换原则

发布时间:2020-12-14 02:02:19 所属栏目:百科 来源:网络整理
导读:例子: 测试代码: #include iostreamusing namespace std;//书类Bookclass Book{private: int width; int height;public: virtual void madeByWood() { cout"I'm made by wood!"; } virtual void setI(int w,int h) { width=w; height=h; } virtual int get

例子:

测试代码:

#include <iostream>

using namespace std;

//书类Book
class Book
{
private:
    int width;
    int height;
public:
    virtual void madeByWood()
    {
        cout<<"I'm made by wood!";
    }
    virtual void setI(int w,int h)
    {
        width=w;
        height=h;
    }
    virtual int getW()
    {
        return width;
    }
    virtual int getH()
    {
        return height;
    }
};

//电子书类E_book
class E_book:public Book
{
public:
    void madeByWood()
    {
        cout<<"I'm not made by wood!";
    }
    void setI(int w,int h)
    {
        Book::setI(0,0);
    }
    int getW()
    {
        return Book::getW();
    }
    int getH()
    {
        return Book::getH();
    }
};

//测试类TextBook
class TextBook
{
public:
    void caleArea(Book &book)
    {
        try
        {
            if(book.getW()==0&&book.getH()==0)
                throw 0;
            int area=book.getW()*book.getH();
            cout<<"书的面积为:"<<area<<endl;
        }
        catch(int)
        {
            cout<<"An error occured!"<<endl;
        }
    }
};

int main()
{
    Book b;
    b.setI(8,12);
    E_book e;
    e.setI(0,0);
    TextBook t;
    t.caleArea(b);
    t.caleArea(e);
    return 0;
}

运行结果:


里氏替换原则:


??

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读