3. Открытое наследование (public inheritance) - отношение "is-a" class Person {}; class Student : public Person {}; class Teacher : public Person {}; void f(Person&) {…} void g() { Student s; Teacher t; f(s); f(t); } Отношение “is-a” организует объекты в виде иерархической классификации.
4.
5.
6.
7.
8. Отношение “is-a” - как можно ошибиться? (1) class StupidBird {public: virtual void fly() = 0;}; class StupidEagle : public StupidBird {public: virtual void fly();}; class StupidPenguin : public StupidBird {public: virtual void fly();}; Пингвины не умеют летать. Как мы собираемся реализовывать Stupid Penguin::fly()?
9. Отношение “is-a” - как можно ошибиться? (2) class Rectangle { public: int getHeight() const; virtual void setHeight(int); int getWidth() const; virtual void setWidth(int); }; void RectangleTest(Rectangle& r) { r.setHeight(4); r.setWidth(5); int S = r.getHeight()*r.getWidth(); assert(S==20); } class Square : public Rectangle { public: void setHeight(int h) { Rectangle::setHeight(h); Rectangle::setWidth(h); } void setWidth(int w) { Rectangle::setWidth(w); Rectangle::setHeight(w); } };
10.
11.
12. Отношение “is-a” - как исправить ошибку? (1) В рамках задачи неверно утверждение «все птицы умеют летать». Значит, неправильно делать fly() методом Bird. Решение из обычного орнитологического определителя: дополнительная теза-антитеза «летает - не летает».
13. Отношение “is-a” - как исправить ошибку? (2) class Rectangular { public: virtual int getHeight() const = 0; virtual int getWidth() const = 0; }; class Square : public Rectangular { public: virtual int getHeight() const; virtual int getWidth() const; void setSide(int s); }; class Rectangle : public Rectangular { public: virtual int getHeight() const; virtual int getWidth() const; void setHeight(int h); void setWidth(int w); };
14.
15.
16.
17.
18.
19.
Editor's Notes
Public vs. protected interface - two types of clients {part. Meyers1.41}. Containment as "has-a" or "is-implemented-via" relationship {Meyers1.40} Private inheritance - reasons of use instead of containment {Meyers1.42}