Lua实现类、以及类的继承:
Point = {} Point.__index = Point function Point:new(x1, y1) local obj = {x = x1 or 0, y = y1 or 0} setmetatable(obj,self) return obj end function Point:describe() print(string.format("Point at (%d, %d)", self.x, self.y)) end -- 定义子类Distance,继承Point Distance = setmetatable({},{__index = Point}) Distance.__index = Distance function Distance:new(x,y) local obj = Point.new(self, x, y) setmetatable(obj, self) return obj end function Distance:distanceTo(other) local dx = self.x - other.x local dy = self.y - other.y return math.sqrt(dx * dx + dy * dy) end local p1 = Distance:new(0, 0) local p2 = Distance:new(1, 1) p1:describe() p2:describe() print(p1:distanceTo(p2))
-- 题目一:封装一个矩形类
-- 要求:
-- 类名:Rectangle
-- 属性:width, height(默认值都是 0)
-- 方法:
-- area():返回面积
-- perimeter():返回周长
local Rectangle = {} Rectangle.__index = Rectangle function Rectangle:new(w, h) local obj = { w = (w and w > 0) and w or 0, h = (h and h > 0) and h or 0 } setmetatable(obj, Rectangle) return obj end function Rectangle:area() return self.w * self.h end function Rectangle:perimeter() return 2 * (self.w + self.h) end local obj = Rectangle:new(2,3) print(obj:area()) print(obj:perimeter())
-- 题目二:实现一个继承关系
-- 要求:
-- 基类:Shape
-- 方法:describe(),输出 "This is a shape."
-- 子类:Circle
-- 属性:radius
-- 重写 describe(),输出 "This is a circle with radius R"
-- 添加方法:area()(使用 π≈3.14)
local Shape = {} Shape.__index = Shape function Shape:describe() print("This is a shape.") end local Circle = setmetatable({}, {__index = Shape}) Circle.__index = Circle function Circle:new(radius) local obj = { radius = (radius and radius > 0) and radius or 1 --默认值为1 } setmetatable(obj, self) return obj end function Circle:describe() print("This is a circle with radius " .. self.radius) end function Circle:area() return 3.14 * self.radius ^ 2 end local obj = Circle:new(2) obj:describe() print(obj:area())
-- 题目三:多级继承
-- 要求:
-- Animal 基类,有属性 name,方法 speak() 打印 "Some generic animal sound"
-- Dog 继承 Animal,重写 speak() 输出 "Woof!"
-- Sheepdog 再继承 Dog,增加方法 guard() 输出 "Guarding the sheep!"
local Animal = {} Animal.__index = Animal function Animal:new(name) local obj = { name = name or "UnKnow" } setmetatable(obj, self) return obj end function Animal:speak() print("Some generic animal sound") end local Dog = setmetatable({},{__index = Animal}) Dog.__index = Dog function Dog:new(name) return Animal.new(self,name) end function Dog:speak() print("Woof") end local Sheepdog = setmetatable({},{__index = Dog}) Sheepdog.__index = Sheepdog function Sheepdog:new(name) return Dog.new(self,name) end function Sheepdog:guard() print("Guarding the sheep!") end local obj = Sheepdog:new("ASheepdog") obj:speak() obj:guard()