[英]Delphi: Method 'Create' hides virtual method of base - but it's right there
Consider the hypothetical object hierarchy, starting with:考虑假设的对象层次结构,从以下开始:
TFruit = class(TObject)
public
constructor Create(Color: TColor); virtual;
end;
and its descendant:及其后代:
TApple = class(TFruit)
public
constructor Create(); overload; virtual;
constructor Create(Color: TColor); overload; override; //deprecated. Calls other constructor - maintaining the virtual constructor chain
end;
The idea here is that I've overridden the virtual constructor of the base class, with an overload that also happens to be virtual.这里的想法是我已经覆盖了基类的虚拟构造函数,重载也恰好是虚拟的。
Delphi complains:德尔福抱怨:
Method 'Create' hides virtual method of base type 'TFruit'
方法“Create”隐藏基类型“TFruit”的虚拟方法
Except it doesn't hide it - it's right there!除了它没有隐藏它 - 它就在那里!
What's the deal?这是怎么回事?
Two solutions:两种解决方案:
type
TFruit = class(TObject)
public
constructor Create(Color: TColor); virtual;
end;
TApple = class(TFruit)
public
constructor Create(); reintroduce; overload;
constructor Create(Color: TColor); overload; override;
end;
Or:要么:
type
TFruit = class(TObject)
public
constructor Create; overload; virtual; abstract;
constructor Create(Color: TColor); overload; virtual;
end;
TApple = class(TFruit)
public
constructor Create(); override;
constructor Create(Color: TColor); override;
end;
This appears to be a "which came first" sort of issue.这似乎是一个“先来”的问题。 (It appears NGLN found a solution.)
(看来 NGLN 找到了解决方案。)
There's another solution, also.还有另一个解决方案。 You can use a default parameter:
您可以使用默认参数:
interface
type
TFruit=class(TObject)
public
constructor Create(Color: TColor); virtual;
end;
TApple=class(TFruit)
public
constructor Create(Color: TColor = clRed); override;
end;
implementation
{ TFruit }
constructor TFruit.Create(Color: TColor);
begin
inherited Create;
end;
{ TApple }
constructor TApple.Create(Color: TColor);
begin
inherited;
end;
// Test code
var
AppleOne, AppleTwo: TApple;
begin
AppleOne := TApple.Create;
AppleTwo := TApple.Create(clGreen);
end;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.