【Lua】题目小练7
Lua实现类、以及类的继承:
Point = {} Point.__index = Pointfunction Point:new(x1, y1)local obj = {x = x1 or 0, y = y1 or 0}setmetatable(obj,self)return obj endfunction Point:describe()print(string.format("Point at (%d, %d)", self.x, self.y)) end-- 定义子类Distance,继承Point Distance = setmetatable({},{__index = Point}) Distance.__index = Distancefunction Distance:new(x,y)local obj = Point.new(self, x, y)setmetatable(obj, self)return obj endfunction Distance:distanceTo(other)local dx = self.x - other.xlocal dy = self.y - other.yreturn math.sqrt(dx * dx + dy * dy) endlocal 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 = Rectanglefunction 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 endfunction Rectangle:area()return self.w * self.h endfunction Rectangle:perimeter()return 2 * (self.w + self.h) endlocal 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 = Shapefunction Shape:describe()print("This is a shape.") endlocal Circle = setmetatable({}, {__index = Shape}) Circle.__index = Circlefunction Circle:new(radius)local obj = {radius = (radius and radius > 0) and radius or 1 --默认值为1}setmetatable(obj, self)return obj endfunction Circle:describe()print("This is a circle with radius " .. self.radius) endfunction Circle:area()return 3.14 * self.radius ^ 2 endlocal 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 = Animalfunction Animal:new(name)local obj = {name = name or "UnKnow"}setmetatable(obj, self)return obj endfunction Animal:speak()print("Some generic animal sound") endlocal Dog = setmetatable({},{__index = Animal}) Dog.__index = Dogfunction Dog:new(name)return Animal.new(self,name) endfunction Dog:speak()print("Woof") endlocal Sheepdog = setmetatable({},{__index = Dog}) Sheepdog.__index = Sheepdogfunction Sheepdog:new(name)return Dog.new(self,name) endfunction Sheepdog:guard()print("Guarding the sheep!") endlocal obj = Sheepdog:new("ASheepdog") obj:speak() obj:guard()