Lua面向对象之继承( Student类继承自Person类)

本文详细介绍了在Lua中如何通过元表和__index元方法实现类的继承,包括定义基类和派生类,以及如何在派生类中重写和扩展基类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承是面向对象中一个很重要的特性,要想在lua中实现该特性也相对比较简单,配合元表和__index元方法,让派生类与基类形成一条链,前面我们学习了Student类,那么我们让Student类继承自Person类,看代码:

 

-----------------基类---------------------
Person = {};

-- 设置__index键为一张表,这个表是自己
Person.__index = Person   --关键


-- 定义类型属性(相当于静态成员变量)
Person.objCount = 0;

-- 定义类方法(相当于静态成员函数)
function Person:Count( )

    print ("一共有".. self.objCount.."个对象!");

end

-- 定义构造函数
function Person:Create()

    Person.objCount = Person.objCount + 1;

    local  instance = {};
    setmetatable(instance, self.prototype); --此处是关键
    print( "-->",self.prototype) --这里如果是派生类Student调用,那么self就是派生类Student
    return instance;

end




-- 定义类型的prototype
Person.prototype = {};

-- 设置prototype的__index元方法
Person.prototype.__index = Person.prototype;

-- 定义实例对象属性
Person.prototype.name = "";

Person.prototype.age = 0;

-- 定义实例对象方法
function Person.prototype:Init( a , n)
     self.age =a;
     self.name =n
end



-- 定义打印方法(使用:)
function Person.prototype:Show()
    print ( "姓名:"..self.name ,"年龄:"..self.age);
end




-----------------派生类---------------------

-- 创建类型并绑定父类作为元表
Student = {};
setmetatable(Student, Person);


-- 创建prototype并绑定父类prototype作为元表
Student.prototype = {  class };
Student.prototype.__index = Student.prototype;
setmetatable(Student.prototype, Person.prototype); -- 关键:  instance 的元表是 Student.prototype ,Student.prototype的元表是Person.prototype
print( ">>>",Student.prototype)


-- 定义打印方法(使用:)
function Student.prototype:Show()
    print ( "姓名:"..self.name ,"年龄:"..self.age , " 班级:"..self.class);
end

--------------测试-----------------------------

local stu1 = Student:Create();
stu1:Init("张三",12) --使用:方式调用
stu1.class ="一年级"
stu1:Show()


local stu2 = Student:Create();
stu2.Init(stu2,"李四",16) -- 使用.方式调用
stu2.class ="二年级"
stu2.Show(stu2)


--模拟类的静态变量、方法
print(Student.objCount)

Student:Count()  --使用:方式调用
Student.Count(Student) -- 使用.方式调用

 运行效果如下:

跟大家做了一张图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员乐逍遥

如果你觉得帮助了你,支持一下!

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

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

打赏作者

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

抵扣说明:

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

余额充值