例子:
测试代码:
#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; }
运行结果:
里氏替换原则:
原文链接:https://www.f2er.com/javaschema/283549.html