关于constructor Create;的重载问题。(100分)

  • 主题发起人 主题发起人 shenger
  • 开始时间 开始时间
S

shenger

Unregistered / Unconfirmed
GUEST, unregistred user!
在system单元的TObject定义中,构造函数只被定义为“constructor Create;”,并无virtual
保留字,那请问:
(1)为何我发现有些子类的constructor Create;可以override它?
(2)就算可以override它,那子类函数的参数应与父类的参数一致(这里是没有),为何我发现
有些子类的constructor Create;可以带参数,如:TShape的定义中
constructor Create(Owner:TConponent);Override;
这是怎么回是?

我买了本烂到家的书。
 
constructor TShape.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
Width := 65;
Height := 65;
FPen := TPen.Create;
FPen.OnChange := StyleChanged;
FBrush := TBrush.Create;
FBrush.OnChange := StyleChanged;
end;
 
Overriding the constructor

When a component is placed on a form at design time, or when an application constructs a component at runtime, the component’s constructor sets the property values. When a component is loaded from a form file, the application sets any properties changed at design time.

Note: When you override a constructor, the new constructor must call the inherited constructor before doing anything else. For more information, see Overriding methods.

For this example, your new component needs to override the constructor inherited from TMemo to set the WordWrap property to False. To achieve this, add the constructor override to the forward declaration, then write the new constructor in the implementation part of the unit:

type

TWrapMemo = class(TMemo)
public { constructors are always public }
constructor Create(AOwner: TComponent)
override
{ this syntax is always the same }
end;
...
constructor TWrapMemo.Create(AOwner: TComponent)
{ this goes after implementation }
begin
inherited Create(AOwner)
{ ALWAYS do this first! }
WordWrap := False
{ set the new desired value }

end;

Now you can install the new component on the Component palette and add it to a form. Note that the WordWrap property is now initialized to False.
If you change an initial property value, you should also designate that value as the default. If you fail to match the value set by the constructor to the specified default value, Delphi cannot store and restore the proper value.
 
注意,TComponent以下的类,Create(AOwner:TComponent) 它override的是
TComponent.Create(AOwner:TComponent);virtual;
这个是virtual的!
而不是orverride TObject的Create
 
1)delphi默认的方法属性为static,这样的方法可以进行方法覆盖(override),覆盖时不用声明为override。这样的方法完全根据所声明的类型进行调用(区别于虚方法的多态)。也就是说调用时点前面的类决定方法属于哪个类。
2)这种情况叫重载(overload),这种声明允许同名但参数表不同的方法在同一类(及其子类)中存在

你的问题,delphi的help里都有.....别怪书不好了
 
根据Pipi.老大的意思,TConponent的Create与TObject的Create没有关系,而是一个重新定义
了的构造函数?并不对它Overrride?
 
对,其他的TComponent继承下来的类,比如TEdit TForm 之类,他的Create(AOwner)都是继承
TComponent.Create(AOwner:TComponent);virtual;

 
接受答案了.
 
后退
顶部