Oop Delphi类变量
我有以下代码:Oop Delphi类变量,oop,delphi,Oop,Delphi,我有以下代码: // irrelevant code ... type Zombie = class private ... Age : Integer; Alive : Boolean; TotalDeadZombies, TotalZombieAge : Double; public ... procedure ZombieGrow(); procedure CheckIfDead(); ... Funct
// 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;
然而,这是在另一个没有显示在这里的类中调用的,从我对OOP的理解来看,它需要我指定一个实例化的对象,例如zombies[1]。AvgLife,如果它们存储在(比如)zombies[]数组中,这只是一个示例
有没有办法使变量TotalDeadZombies和TotalZombieAge不绑定到任何实例化的zombies,而是绑定到一个类变量,然后我可以以某种方式调用AvgLife?它是否像让它们成为全局变量一样简单?或者可以用另一种方法吗?您只需将变量声明为类var;然后它们属于类,而不是类的特定实例
type
TZombie = class
public
class var TotalDeadZombies, TotalZombieAge: Double;
end;
你可以像TZombie.TotalDeadZombies一样访问这些。类似地,还有类方法、类属性等
看一看
type
TZombie = class
public
class var TotalDeadZombies, TotalZombieAge: Double;
end;