Delphi: Understanding constructors

后端 未结 4 1555
有刺的猬
有刺的猬 2020-11-30 23:28

i\'m looking to understand

  • virtual
  • override
  • overload
  • reintroduce

when applied to object constructors. Every

4条回答
  •  隐瞒了意图╮
    2020-12-01 00:01

    Note that I don't have Delphi 5, so I'm basing my answers off the newest version, Delphi XE. I don't think that will really make any difference here, but if it does, you've been warned. :)

    This is mostly based on http://docwiki.embarcadero.com/RADStudio/en/Methods, which is the current documentation of how methods work. Your Delphi 5 help file probably has something similar to this as well.

    First off, a virtual constructor may not make much sense here. There are a few cases where you do want this, but this probably isn't one. Take a look at http://docwiki.embarcadero.com/RADStudio/en/Class_References for a situtation where you do need a virtual constructor - if you always know the type of your objects when coding, however, you don't.

    The problem you then get in your 1-parameter constructor is that your parent class doesn't have a 1-parameter constructor itself - inherited constructors are not exposed. You can't use inherited to go up multiple levels in the hierarchy, you can only call your immediate parent. You will need to call the 2-parameter constructor with some default value, or add a 1-parameter constructor to TCellPhone as well.

    In general, the four keywords have the following meanings:

    • virtual - Mark this as a function where you will want run-time dispatching (allows polymorphic behavior). This is only for the initial definition, not when overriding in subclasses.
    • override - Provide a new implementation for a virtual method.
    • overload - Mark a function with the same name as another function, but a different parameter list.
    • reintroduce - Tell the compiler you actually intended to hide a virtual method, instead of merely forgetting to supply override.

    The ordering required is detailed in the documentation:

    Method declarations can include special directives that are not used with other functions or procedures. Directives should appear in the class declaration only, not in the defining declaration, and should always be listed in the following order:

    reintroduce; overload; binding; calling convention; abstract; warning

    where binding is virtual, dynamic, or override; calling convention is register, pascal, cdecl, stdcall, or safecall; and warning is platform, deprecated, or library.

提交回复
热议问题