Delphi子类调用祖父类的虚函数
2016-12-07 22:32
288 查看
因为看Delphi书的时候,就产生了疑惑。老讲调用父类虚函数,但是万一需要调用祖父虚函数怎么办?
后来又经常在C++里看到,就更疑惑了
利用了 Delphi 能够创建纯虚函数实例的特性
记录下了TA的函数地址
然后替换其Data的值为Self,然后在需要的时候再调用
利用了两点:TMethod和Delphi能够创建纯虚类实例
只是说万一纯虚的话,这个也好使
感谢 [长春]swish
----------------------------------------------------------
另一种办法:
http://stackoverflow.com/questions/4662744/delphi-how-to-call-inherited-inherited-ancestor-on-a-virtual-method
诀窍是搜索关键字“delphi inherited super parent”
后来又经常在C++里看到,就更疑惑了
type TA = class procedure ShowMsg; virtual; end; TAClass = class of TA; TB = class(TA) procedure ShowMsg; override; end; TShowMsg = procedure of object; TC = class(TB) private FGrandFatherShowMsg: TShowMsg; procedure ShowMsg; override; public constructor Create; end; procedure TForm2.Button1Click(Sender: TObject); var C: TC; begin C := TC.Create; C.ShowMsg; C.Free; end; { TC } constructor TC.Create; var AMethod:TShowMsg; ACode: TMethod absolute AMethod; A: TA; begin inherited Create; A := TA.Create; FGrandFatherShowMsg := A.ShowMsg; AMethod:= FGrandFatherShowMsg; ACode.Data := Self; A.Free; end; procedure TC.ShowMsg; begin FGrandFatherShowMsg; ShowMessage('TC'); end; { TA } procedure TA.ShowMsg; begin ShowMessage('TA'); end; { TB } procedure TB.ShowMsg; begin inherited; ShowMessage('TB'); end;
利用了 Delphi 能够创建纯虚函数实例的特性
记录下了TA的函数地址
然后替换其Data的值为Self,然后在需要的时候再调用
利用了两点:TMethod和Delphi能够创建纯虚类实例
只是说万一纯虚的话,这个也好使
感谢 [长春]swish
----------------------------------------------------------
另一种办法:
type TBase = class procedure Foo; virtual; end; TAnsestor = class(TBase) procedure Foo; override; end; TChild = class(TAnsestor) procedure Foo; override; procedure BaseFoo; end; procedure TBase.Foo; begin ShowMessage('TBase'); end; procedure TAnsestor.Foo; begin ShowMessage('TAnsestor'); end; procedure TChild.Foo; begin ShowMessage('TChild'); end; type TFoo = procedure of object; procedure TChild.BaseFoo; var Proc: TFoo; begin TMethod(Proc).Code := @TBase.Foo; // Static address TMethod(Proc).Data := Self; Proc(); end; procedure TForm4.Button1Click(Sender: TObject); var Obj: TChild; Proc: TFoo; begin Obj:= TChild.Create; Obj.BaseFoo; // or else TMethod(Proc).Code := @TBase.Foo; // Static address TMethod(Proc).Data := Obj; Proc(); Obj.Free; end;
http://stackoverflow.com/questions/4662744/delphi-how-to-call-inherited-inherited-ancestor-on-a-virtual-method
诀窍是搜索关键字“delphi inherited super parent”
相关文章推荐
- Delphi驱动开发研究第一篇--实现原理
- Delphi完成的断点续传例子 转
- Delphi自带的字符串分割函数Split
- delphi IOS 获取电池信息
- Delphi中GetTickCount函数的使用
- advstringGrid列不见了
- Delphi中如何将 Exe 程序或其他资料打包在内,使用时再释放使用(转)
- DELPHI高性能大容量SOCKET并发(九):稳定性问题解决
- Delphi 文件目录函数大全
- delphi 调用百度地图WEBSERVICE转换GPS坐标 转
- delphi 调用百度地图api
- delphi -- GDi+ Delphi如何让 TGPImage 直接从流中加载图片
- Delphi判断文件是否正在被使用
- Delphi2010开发DataSnap服务器(一)
- delphi FMX 数字下拉滑动
- 什么是验证码识别程序?
- Delphi编写DLL供C#调用的实例
- Delphi调用C# 编写dll动态库
- Delphi调用C# 编写dll动态库
- NN远程桌面SDK之Delphi开发源码