2015-09-03 71 views
6

这似乎是一个非常愚蠢的问题,但我不知道这是为什么,甚至允许编译:为什么Delphi允许构造函数参数不正确?

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并没有对其它版本测试。 谢谢。

回答

8

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

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

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; 

我个人更喜欢使双方实现和接口声明的比赛,因为它可以更容易识别参数,而不用在代码编辑器中跳过。

+0

谢谢肯,我已经使用了德尔福15年,我不知道这一点!我同意 - 我更喜欢接口来匹配实现。我认为唯一不合时宜的是重载方法? –

+2

TurboPASCAL 5.0引入了这个。 –

+0

请注意,如果未指定参数(如果指定了它们必须匹配或者编译器会抱怨),编译器才会允许这样做。这是Pascal的一个语言功能,在Delphi之前。 –

相关问题