德尔福类变量
问题描述:
我有以下代码:德尔福类变量
// irrelevant code ...
type
Zombie = class
private
...
Age : Integer;
Alive : Boolean;
TotalDeadZombies, TotalZombieAge : Double;
public
...
procedure ZombieGrow();
procedure CheckIfDead();
...
Function AvgLife() : Double;
end;
procedure Zombie.ZombieGrow();
begin
...
if (Alive = false) then
begin
TotalDeadZombies := TotalDeadZombies + 1;
TotalZombieAge := TotalZombieAge + Age;
end;
end;
procedure Zombie.CheckIfDead();
begin
if Random(100) < 20 then
Alive := False;
end;
function Zombie.AvgLife() : Double;
begin
Result := TotalZombieAge/TotalDeadZombie;
end;
我的问题是,我想显示死僵尸的平均年龄。这将通过像这样做:
Write('Average age '+Floattostr(Round(AvgLife)))
然而,这就是所谓的另一个类(这里没有显示),并从我的OOP的理解,它需要我,如果指定一个实例化的对象,如zombies[1].AvgLife
他们被存储在例如Zombies[]
数组中(只是一个例子)。
有没有办法使得变量TotalDeadZombies
和TotalZombieAge
不绑定到任何实例化的僵尸,而是一个类变量,然后我可以以某种方式调用AvgLife
?它只是简单地把它们变成全局变量吗?或者可以以另一种方式做到吗?
答
你只需要声明变量为class var
;那么它们属于类别,而不属于某个类别的特定实例。
type
TZombie = class
public
class var TotalDeadZombies, TotalZombieAge: Double;
end;
您可以像TZombie.TotalDeadZombies
那样访问这些文件。同样,也有类方法,类属性等。