Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

overloading - 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'

Except it doesn't hide it - it's right there!

  • I overrode the virtual method in the ancestor, and
  • I overloaded it with another version

What's the deal?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...