You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Delphi中调用虚方法的当前层级(非多态)版本?

在Delphi中调用虚方法的当前层级(非多态)版本

类定义

Parent = class
public
  procedure virtFunc(); virtual;
  procedure other();
end;

Child = class(Parent)
public
  procedure virtFunc(); override;
end;

需求场景

通常调用Child实例的virtFunc时,会执行Child中的重写实现。但在Parent的other方法中,希望调用Parent自身的virtFunc实现,而非被Child重写的版本:

procedure Parent.other();
begin
  virtFunc(); // 此处希望执行Parent.virtFunc(),而非Child.virtFunc()
end;

已尝试的无效方法

  • Parent(Self).virtFunc()
  • (Self as Parent).virtFunc()

不考虑的替代方案

  • 为方法重命名(如区分childFunc和parentFunc)
  • 移除virtual修饰符

解决方案

在Delphi中,要实现类似C++里Parent::virtFunc()的非多态调用,直接通过类名+方法名的方式显式调用,并传入Self参数即可:

procedure Parent.other();
begin
  Parent.virtFunc(Self); // 直接调用Parent类的virtFunc实现,绕过虚表
end;

这种写法会跳过虚方法的多态机制,无论当前Self实际指向Parent还是Child实例,都会执行Parent类中定义的virtFunc实现。


内容的提问来源于stack exchange,提问作者Adrian Maire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:00:50