码迷,mamicode.com
首页 > 编程语言 > 详细

C++多态

时间:2015-09-10 12:33:48      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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);
}

 

C++多态

标签:

原文地址:http://www.cnblogs.com/dejunwang/p/4797115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!