美文网首页
Lua创建一个类 继承

Lua创建一个类 继承

作者: 某人在 | 来源:发表于2018-05-22 15:08 被阅读27次

    创建一个类

    ~~~ lua

    -- 定义名为 Shape 的基础类 

    [csharp] view plain copy

    local Shape = class("Shape")  

    -- ctor() 是类的构造函数,在调用 Shape.new() 创建 Shape 对象实例时会自动执行

    [csharp] view plain copy

    function Shape:ctor(shapeName)  

        self.shapeName = shapeName  

    printf("Shape:ctor(%s)", self.shapeName)  

    end  

    -- 为 Shape 定义个名为 draw() 的方法

    [csharp] view plain copy

    function Shape:draw()  

    printf("draw %s", self.shapeName)  

    end  

    -- Circle 是 Shape 的继承类

    [csharp] view plain copy

    local Circle = class("Circle", Shape)  

    function Circle:ctor()  

        -- 如果继承类覆盖了 ctor() 构造函数,那么必须手动调用父类构造函数  

        -- 类名.super 可以访问指定类的父类  

    Circle.super.ctor(self,"circle")  

        self.radius = 100  

    end  

    function Circle:setRadius(radius)  

        self.radius = radius  

    end  

    -- 覆盖父类的同名方法

    [csharp] view plain copy

    function Circle:draw()  

    printf("draw %s, raidus = %0.2f", self.shapeName, self.raidus)  

    end  

    相关文章

      网友评论

          本文标题:Lua创建一个类 继承

          本文链接:https://www.haomeiwen.com/subject/bznhjftx.html