【翁恺】20-多态性

本文探讨了C++中的继承概念,如何定义圆形、椭圆和矩形作为形状的派生类,并使用多态实现render方法的动态绑定。通过upcast和virtual关键字展示了基类Shape和其子类间的交互,以及静态与动态绑定的区别。
摘要由CSDN通过智能技术生成

a drawing program

  • data
    • center
  • operatons
    • render
    • move
    • resize

Inheritance in C++

  • can define one class in term of another
  • can capture the notion that
    • an ellipse is a shape
    • a circle is a special kind of ellipse
    • a rectangle is a different shape
    • circles,ellipses,and rectangles share common
      • attributes
      • services
    • circles,ellipses,and rectangles are not identical(同一的)

conceptual(概念) model

 render 不同

shape

  • define the general properties of shape

    class XYPos{...};//x,y point
    class shape{
    public:
        Shape();
        virtual ~Shape();
        virtual void render(); // virtual 子类和父类的同名函数联系在一起
        void move(const XYPos&);
        virtual void resize();
    protected:
        XYPos center;
    }

add new shapes

class Ellipse:public Shape{
public:
    Ellipse(float maj,float mint);
    virtual void render();//will define own  virtual不加也是virtual的,好习惯,不用看shape
protected:
    float major_axis,minor_axis; 
};

class Circls:public Ellipse{
public:
	Circle(float radius):Ellispse(radius,radius){}
    virtual void render();
};

Example

void render(Shape* p){ // 通用函数
    p->render();	//calls correct render function for given shape
}	
// p的静态类型是 shape 的指针;p的动态类型指的是 p当时指的对象的类型是什么。如果render是virtual 是动态绑定,取决于render;不是virtual是静态绑定。
void func(){
    Ellipse ell(10,20);
    ell.render();
    
    Circle circ(40);
    circ.render();
    
    render(&ell); // virtual作用:运行时候确定调用哪个函数,这里调用 ell 的函数
    reder(&circ);
}

p是多态的,p指的谁,变成谁的形态。

poly多morphism形态 (多态性)

  • upcast: take an object of the derived class as an object of base one

    • Ellipse can be treaded as a Shape

upcast: 把子类对象当作父类看待

  • dynamic binging(动态绑定)

    • binding:which function to be called
      • static binding:call the function as the code
      • dynamic binding:call the function of the object

绑定:调用函数时候应调用哪个函数,叫做绑定

静态绑定:调的函数在编译时候确定

动态绑定:运行时候才知道调用哪个函数,根据指针所指的对象决定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理心炼丹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值