# 设计模式六大原则:里氏替换原则(五)

``````//
// 里氏替换原则.cpp
// c++
//
// Created by 刘龙玲 on 16/5/12.
//

#include <iostream>
using namespace std;

//案例：鸵鸟非鸟
class Bird
{
public:
bool fly() {
//鸟类可以飞;
return true;
};
int getVelocity()
{
return this->velocity;
}
private:
int velocity;
};

//鸵鸟
class Ostrich: public Bird
{
bool fly() {
//鸵鸟不可以飞;
return false;
};
int getVelocity()
{
return 0;
}
};

int main()
{
//计算鸟飞越黄河所需的时间。
Bird* bird = new Ostrich;
cout<<"h:"<<3000/bird->getVelocity()<<endl;
return 0;
}``````

“low-level events, such as arithmetic overflows and divide by zero, are assumed to be handled by a dedicated lower-level mechanism rather than by exceptions. This enables C++ to match the behaviour of other languages when it comes to arithmetic. It also avoids the problems that occur on heavily pipelined architectures where events such as divide by zero are asynchronous.”

``````package com.lll.test;
//鸟
public class Bird {
private int velocity;

public int getVelocity() {
return velocity;
}

public void setVelocity(int velocity) {
this.velocity = velocity;
}
}``````
``````package com.lll.test;
//鸵鸟
public class Ostrich extends Bird{

public int getVelocity() {
return 0;
}
}
``````
``````package com.lll.test;

public class main {

public static void main(String[] args) {
Bird bird = new Bird();
bird.setVelocity(100);
int h = flyTime(bird);
System.out.println("飞行时间是:"+h);
}

public static int flyTime(Bird bird)
{
return 3000/bird.getVelocity();
}
}
``````

``````package com.lll.test;

public class main {

public static void main(String[] args) {
Bird bird = new  Ostrich();
bird.setVelocity(100);
int h = flyTime(bird);
System.out.println("飞行时间是:"+h);
}

public static int flyTime(Bird bird)
{
return 3000/bird.getVelocity();
}
}``````

Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.lll.test.main.flyTime(main.java:11)
at com.lll.test.main.main(main.java:7)

原文作者：程序员小毛驴
原文地址: https://blog.csdn.net/liulongling/article/details/51383159
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。