加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么Delphi允许构造函数参数不正确?

发布时间:2020-12-15 04:35:24 所属栏目:大数据 来源:网络整理
导读:这似乎是一个非常愚蠢的问题,但我不知道为什么甚至允许编译: program ConstructorWithParam;{$APPTYPE CONSOLE}uses System.SysUtils;type TThing = class(TObject) private FParent: TObject; public constructor Create(const AParent: TObject); end;{ T
这似乎是一个非常愚蠢的问题,但我不知道为什么甚至允许编译:
program ConstructorWithParam;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type

  TThing = class(TObject)
  private
    FParent: TObject;
  public
    constructor Create(const AParent: TObject);
  end;

{ TThing }

constructor TThing.Create; // <- WTF? Why does the compiler not complain?
begin
  FParent := AParent;
end;

var
  Thing: TThing;
begin
  try
    Thing := TThing.Create(TObject.Create);
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName,': ',E.Message);
  end;
end.

我正在使用Delphi XE5并且没有在其他版本上测试过.
谢谢.

解决方法

表单类中的第一个声明被认为是正确的.实现版本不需要识别所需的参数;它们是由原始声明承担的.这是语言本身的一部分.

这是一个很好的例子来说明这一点:

type
  TMyClass = class (Tobject)
    procedure DoSometimg(DoA,DoB: Boolean);
  end;

执行:

procedure TMyClass.DoSomething;   // Note both parameters missing
begin
  if DoA then    // Note not mentioned in implementation declaration
    DoOneThing;   // but still can be used here
  if DoB then
    DoAnotherThing;
end;

我个人更喜欢使实现和接口声明匹配,因为它使得更容易识别参数而不会在代码编辑器中跳转.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读