Lua面向对象写Student类( 模拟类方法与对象方法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HQ354974212/article/details/89421775

前面我们写出了一个简单的类Student,但是我们发现,我们直接使用Student也可以调用对象方法,这里和我们们学过的其它语言的面向对象还是有些出入的(比如C++,JAVA ,C#  , 类名称是无法调用对象的方法与属性),所以这里改造一下,让类方法、类变量, 与  对象方法,对象变量 分离。

 代码如下:


-- 定义类型
Student = {}; 

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

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

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

end

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

    Student.objCount = Student.objCount + 1;

    local  instance = {};
    setmetatable(instance, self.prototype); --关键,instance可访问prototype的属性,方法
    return instance;

end



-- 定义类型的prototype , 这里的prototype可以随意命名,并非关键字
Student.prototype = {};

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

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

Student.prototype.age = 10;

-- 定义实例对象方法
function Student.prototype:Init( a , n)
    self.age =a;
    self.name =n
end
-- 定义打印方法(使用:)
function Student.prototype:Show()
    print ( "姓名:"..self.name ,"年龄:"..self.age);
end


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


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

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

--模拟类的静态变量、方法
print(Student.objCount)
Student:Count()  --使用:方式调用
Student.Count(Student) -- 使用.方式调用

运行结果图如下:

大家结合这张图看:

猜你喜欢

转载自blog.csdn.net/HQ354974212/article/details/89421775