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

LSP里氏替换原则----正方形不是长方形和鸵鸟不是鸟的测试程序

发布时间:2020-12-13 19:44:12 所属栏目:百科 来源:网络整理
导读://面向对象设计原则:LSP里氏替换原则//正方形不是长方形的测试程序#include iostreamusing namespace std;//长方形类Rectangleclass Rectangle {private:int width;int height;public:int getWidth(){ return width; }virtual void setWidth(int w){ width=
//面向对象设计原则: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()<<"  width="<<objRect.getWidth()<<endl;;
    }
};

//主函数
int main()
{
  Rectangle r;    //父类对象      
  r.setWidth(5);
  r.setHeight(15);
 
  Square s;    //子类对象      
  s.setWidth(5);
  s.setHeight(15);

  TestRectangle t;
  t.resize(r); //ok
  t.resize(s); //用子类对象代替父类对象时,出现无限循环

  return 0;
}


(2)

//面向对象设计原则:LSP里氏替换原则  
//鸵鸟不是鸟的测试程序
#include <iostream>
using namespace std;

//鸟类Bird
class Bird 
{ 
 private:
   double velocity;
 public:
   virtual void  fly() { cout<<"I can fly!"; }
   virtual void  setVelocity(double v)  { velocity = v; }
   virtual double  getVelocity() { return velocity; }
};

//鸵鸟类Ostrich
class Ostrich :public Bird 
{ public: 
   void fly() { cout<<"i can't fly!"; }
   void setVelocity(double v) { Bird::setVelocity(0); }
   double getVelocity() { return Bird::getVelocity(); }
};

//测试类TestBird:
class TestBird
{public:
    void calcFlyTime(Bird &bird)
    {try
 {double riverWidth = 3000;
     if(bird.getVelocity()==0) throw 0;
  cout<<"Velocity="<<bird.getVelocity()<<endl;
  cout<<"Fly time="<<riverWidth/bird.getVelocity()<<endl;
 } catch(int)
 { cout<<"An error occured!"<<endl;  }   
 }
};


//主函数
int main()
{
  Bird b; //父类对象
  b.setVelocity(100);
  Ostrich o;
  o.setVelocity(0);
  TestBird t;
  t.calcFlyTime(b); //ok
  t.calcFlyTime(o); //用子类对象代替父类对象时,出现异常
  return 0;
}



 

 

(编辑:李大同)

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

    推荐文章
      热点阅读