L10.面向对象
--父类 local ParentClass = { id = "085", name = "紫霞", --ParentClass.__index = ParentClass #自索引错误写法, __index赋值的是一个nil值, 也就是说ParentClass是一个nil值 } --[[ function ParentClass.showInfo() --#报错, "."不支持self, 必须是":"调用才支持self printEx("编号:" .. self.id .. " 名字:" .. self.name) end --]] function ParentClass:showInfo() --为什么会在外面单独赋值, 而不是写在ParentClass表里面赋值, 因为没有这种写法, 必须写在外面赋值 printEx("编号:" .. self.id .. " 名字:" .. self.name) end ParentClass.__index = ParentClass --自索引 --写在自索引赋值后面子类继承后依旧可以调用此函数 function ParentClass:method() printEx("我是父类的方法") end --ParentClass.showInfo() #报错, .不支持self, 必须是:调用才支持 ParentClass:showInfo() --子类 local SonClass = { id = "1085", name = "紫霞的儿子" } function SonClass:showInfo() --显示信息方法重写 printEx("编号:" .. self.id .. " 名字:" .. self.name) end SonClass:showInfo() --子类继承父类需要用到元表中的__index 或者 传参(不推荐) setmetatable(SonClass, ParentClass) --子类继承父类中的字段 --调用子类重写的showInfo方法 SonClass:showInfo() --调用继承父类的method方法 SonClass:method()
--实例化 local comClass = {id = "000", name = "无", age = 0} function comClass:showInfo() printEx("id: " .. self.id .. ", 名字: " .. self.name .. ", 年龄: " .. self.age) end function comClass:new(obj) --下面这行代码的含义: 避免多重继承时, 导致self(谁调用就是谁)没有__index无法串连起来 self.__index = rawget(self, __index) or self --返回具有元表的表(继承) return setmetatable(obj or {}, self) end comClass.__index = comClass --实例化1(继承通用类) local instantiation1 = comClass:new({id = "001", name = "熏悟空", age = 85838}) print(instantiation1:showInfo()) --实例化2(继承通用类) local instantiation2 = comClass:new({id = "002", name = "花蝴蝶", age = 547}) print(instantiation2:showInfo()) --实例化3(继承实例化1类, 间接继承通用类) local instantiation3 = instantiation1:new({id = "003", name = "猿猴", age = 192}) print(instantiation3:showInfo())
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了