为什么缺少可选参数会导致“不兼容类型”错误

时间:2013-05-28 14:23:00

标签: delphi generics optional-parameters type-constraints

当我省略构造函数的可选参数时,有人可以解释为什么我在以下程序中遇到“不兼容类型”错误(Delphi XE3)(请参阅代码底部的注释以获取详细信息)?

program Test;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Classes;

type
  BaseClass = class(TObject);

  ChildClass = class(BaseClass);

  GenericBaseClass<T> = class
  public
    constructor Create(Fixed: Integer);
  end;

  GenericClass<T: BaseClass> = class(GenericBaseClass<T>)
  public
    type
      TMyProc = procedure (DataObject: T) of object;
  public
    constructor Create(Fixed: String; Optional: TMyProc = nil);
  end;

constructor GenericClass<T>.Create(Fixed: String; Optional: TMyProc);
begin
  inherited Create(12);
end;

constructor GenericBaseClass<T>.Create(Fixed: Integer);
begin
  inherited Create();
end;

var
  Gc: GenericClass<ChildClass>;

begin
  // this call is okay
  Gc := GenericClass<ChildClass>.Create('', nil);
  // this call fails: E2010 Incompatible types: 'ChildClass' and 'T'
  Gc := GenericClass<ChildClass>.Create('');
end.

1 个答案:

答案 0 :(得分:0)

reintroduceoverload添加到GenericClass构造函数,因为您有多个具有相同名称但参数不同的构造函数。