//面向对象设计原则:LSP里氏替换原则
//正方形不是长方形的测试程序
#include <iostream>
using namespace std;
//长方形类Rectangle
class Rectangle
{
private:
int width;
int height;
public:
int getWidth(){ return width; }
virtual void setWidth(int w){ width=w; }
int getHeight(){ return height; }
virtual void setHeight(int h){ height=h; }
};
//正方形类Square
class Square :public Rectangle
{public:
void setWidth(int w)
{Rectangle::setHeight(w);
Rectangle::setWidth(w);
}
void setHeight(int h)
{Rectangle::setHeight(h);
Rectangle::setWidth(h);
}
};
//测试类 TestRectangle
class TestRectangle
{ public:
void resize(Rectangle &objRect)
{while(objRect.getWidth() <= objRect.getHeight() )
{objRect.setWidth( objRect.getWidth() + 1 );}
cout<<"resize over!"<<endl;
cout<<"height="<<objRect.getHeight()<<" widt
LSP里氏替换原则----正方形不是长方形和鸵鸟不是鸟的测试程序
最新推荐文章于 2024-06-02 21:32:17 发布
本文通过实例探讨了里氏替换原则(LSP)在编程中的应用,通过比较正方形和长方形的关系,揭示了遵循LSP的重要性,并指出为何在某些情况下,正方形不能简单被视为长方形的特例。同时,类比到动物分类,解释了为何鸵鸟不符合鸟类的抽象行为,以此来加深对LSP原则的理解。
摘要由CSDN通过智能技术生成