您的位置:首页 > 编程语言 > C语言/C++

C++多态

2015-09-10 10:52 204 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: