【问题标题】:why does a missing optional parameter cause an "Incompatible types" error为什么缺少可选参数会导致“不兼容的类型”错误
【发布时间】:2013-05-23 13:41:25
【问题描述】:

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

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.

【问题讨论】:

  • 错误信息提示我泛型类型的实例化不适用于默认参数,GenericClass&lt;ChildClass&gt; 的默认参数仍然是 GenericClass&lt;T&gt;.TMyProc 类型的常量 nil,而不是GenericClass&lt;ChildClass&gt;.TMyProc 类型的预期常量 nil。你能通过测试非依赖类型的默认参数是否有效来检查吗?
  • 非依赖类型似乎有效(例如,当我将 Optional 参数的类型从 TMyProc 更改为 Pointer 时,它有效)您的解释听起来很合理,谢谢。

标签: delphi generics optional-parameters type-constraints


【解决方案1】:

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

【讨论】:

  • 我阅读问题的方式,隐藏基类构造函数是故意的,所以overload 是错误的。而reintroduce 除了抑制类声明的警告之外应该没有任何作用,不是吗?
猜你喜欢
  • 2011-11-05
  • 2013-12-16
  • 1970-01-01
  • 2013-06-23
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 2021-07-25
相关资源
最近更新 更多