freepascal - 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)是否在方法分派方面采用其他策略?
解决方案
从文档中:
“对于对象,使用关键字 virtual 在后代对象中重新声明相同的方法来覆盖它就足够了”
这正是你正在做的。因此,您的 Describe 方法是动态调度的,尽管 Box 对象是静态分配的(两者不是 ra。如果您希望它静态调度,则不要使用虚拟方法。
推荐阅读
- python - ImportError:无法从“sklearn”导入名称“cross_validation”
- java - 继承的抽象颜色 - 困惑?
- javascript - 如何连续将对象添加到 Firestore 中的嵌套集合
- python - 即使使用 asyncio 和 aiohttp,方法也会等待请求响应
- asp.net-core - 为什么 Url.EmailConfirmationLink 返回 null
- javascript - React Native - 为两个函数设置顺序
- python - ImportError: `iplot` 只能在 IPython Notebook 中运行
- spring - RepositoryRestController 链接自身和实体名称相同的 url
- python-3.x - 如何获取 matplotlib OHLC 烛台图的 y 轴显示以显示 OHLC 值而不是 y 轴光标位置
- python - 我正在尝试从 goodreads API 获取 json 文件,但我的代码没有读取文件