Lua的面向对象实现-例子补充

--基类
shape={area=0}
function shape:new( o,side )
	o=o or{}
	setmetatable(o,self) --将自己设为o的元表,如果o不为空,则自己为o的父类
	self.__index=self
	side=side or 0
	self.area=side*side
	return o
end

//查找过程:
//从o表中查找,找不到元素,再到self表中找

function shape:printArea()
	print("基类的面积为:",self.area)
end

myshape=shape:new(nil,10)
myshape:printArea()

--派生正方形
square=shape:new()
--派生类的方法new
function square:new(o,side )
	o=o or shape:new(o,side)
	setmetatable(o,self) --将自己设为父类的表的元表,相当于自己为父类表的扩展
	self.__index=self
	return o
end 
--派生类的方法 printArea
function square:printArea( )
	print("正方形的面积:",self.area)
end
//查找过程:
//从o表中查找,找不到元素,再到self表中找

mysquare=square:new(nil,20)
mysquare:printArea()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值