Polymorphism(多态)
Upcast:take an object of the derived class as an object of the base one.
-Ellipse can be treated as a Shape
Dynamic binding(动态绑定)
-Binding:which function to be called
-Static binding: call the function as the code(静态绑定,编译的时已经确定,)
-Dynamic binding: call the function of the object(动态绑定,运行时根据指针所指向的对象来确定call哪个函数k,跟virtual render()有关系)
class XYPos{};//xy,point class Shape { public: Shape(); virtual ~Shape();//虚函数,子类 和 父类的函数有关系 virtual void render(); void move(const XYPos &); virtual void resize(); protected: XYPos center; }; class Ellipse : public Shape { public: Ellipse(float maj, float minr); virtual void render();//will define own protected: float major_axis, minor_axis; }; class Circle : public Ellipse { public: Circle(float radius) : Ellipse(radius, radius){}; virtual void render(); }; void render(Shape* p) { p->render();//根据给定的形状调用正确的render函数; } void func() { Ellipse ell(10,20); ell.render(); circle circ(40); circ.render(); render(&ell); render(&circ); }
晚来一阵风兼雨