首页 > 解决方案 > Pascal 中的静态调度

问题描述

我有一个简单的盒子类层次结构,如下所示:

type
  Box = object

    (* v := value; *)
    constructor Init(value: integer);

    (* WriteLn('this box contains a ', v); *)
    procedure Describe; virtual;

    protected
    var v: integer;

  end;

  SpecialBox = object(Box)

    (* implementation sets value and otherValue *)
    constructor Init(value: integer, otherValue: integer);

    (*  WriteLn('this special box contains ', v, ' and ', v2); *)
    procedure Describe; virtual;

    protected
    var v2: integer;

  end;

我省略了(琐碎的)实现,因为我不想用 Pascal 的冗长语法混淆这个问题。无论如何,我有以下程序:

procedure printBox(box: Box); begin
  box.Describe;
end;

请注意,该过程使用静态分配的Box. 对于像 C++ 这样的语言,我希望调用box.Describe静态链接到Box类中的方法。相反,我在控制台中看到的结果是

'this special box contains <the value of v> and <garbage because v2 is sliced off>'

因此我的问题是:Pascal(或特别是 FPC)是否在方法分派方面采用其他策略?

标签: freepascal

解决方案


文档中:

“对于对象,使用关键字 virtual 在后代对象中重新声明相同的方法来覆盖它就足够了”

这正是你正在做的。因此,您的 Describe 方法是动态调度的,尽管 Box 对象是静态分配的(两者不是 ra。如果您希望它静态调度,则不要使用虚拟方法。


推荐阅读