谁能解释一下,虚拟构造函数的意义是什么?
虚拟函数的用处就是可以在子类通过覆盖扩展父类的行为实现多态的调用,比如我使用
Control.paint,那么每个具体的控件会进行自己的paint
问题是在delphi中,构造函数总是使用类来调用:
aForm := TFrom.Create;
aForm1 := TForm1.Create;
那么这里Create虚拟有什么用呢,因为没有多态调用的机会
虚拟函数的用处就是可以在子类通过覆盖扩展父类的行为实现多态的调用,比如我使用
Control.paint,那么每个具体的控件会进行自己的paint
问题是在delphi中,构造函数总是使用类来调用:
aForm := TFrom.Create;
aForm1 := TForm1.Create;
那么这里Create虚拟有什么用呢,因为没有多态调用的机会
虚拟函数
虚拟构造函数
前兩個, 是不同的概念!
>>子类通过覆盖扩展父类的行为实现多态的调用
>>那么这里Create虚拟有什么用呢,因为没有多态调用的机会
你的理解不對!! 多态的實現與這個無觀!!
http://www.vchelp.net/itbookreview/view_paper.asp?paper_id=831
有你想要知道的
则该函数会覆盖父窗体的func_1,实际执行的是继承窗体的func_1
var
Instance: TComponent; // TComponent 的 constructor 是 virtual
begin
Instance := TComponent(InstanceClass.NewInstance);
TComponent(Reference) := Instance;
try
Instance.Create(Self); // 这个地方实际上调用了派生类的 constructor
except
TComponent(Reference) := nil;
raise;
end;
if (FMainForm = nil) and (Instance is TForm) then
begin
TForm(Instance).HandleNeeded;
FMainForm := TForm(Instance);
end;
end;
1.不是类方法,但可以同时被类引用(这里指类名称,而不是类引用类型)和对象引用进行调用----如果是其他非类方法的方法成员在使用类引用进行调用的时候马上会编译出错:This form of method call only allowed for class methods.
2.申明方式特殊:构造器其实是一个函数,因为它返回一个对象引用,但定义方式不需要定义返回值类型,而且使用特殊的关键字Constructor.所以,如果是用类引用来调用构造器是肯定无法实现多态的,但如果使用对象引用来进行构造器的调用就可以很容易的实现多态,和普通对象方法一样....但即使使用类引用(类名称无法实现多态),但如果使用一个类引用类型的变量同样可以实现多态,如下:type TControlClass = class of TControl; //创建一个类引用类型
....
function CreateControl(ControlClass: TControlClass;
const ControlName: string; X, Y, W, H: Integer): TControl;
begin
Result := ControlClass.Create(MainForm); //通过一个类引用类型变量来调用构造器,而不是通过一个确定的类名称(其实也是一种引用)来调用,这样同样可以实现多态!
with Result do
begin
Parent := MainForm;
Name := ControlName;
SetBounds(X, Y, W, H);
Visible := True;
end;
end;
....
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TBase = class
constructor Create; virtual;
end; TInherited = class(TBase)
constructor Create;
end;
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
procedure ShowAddress(o: TObject);
public
{ Public declarations }
end;var
Form1: TForm1;implementation{$R *.dfm}
constructor TBase.Create;
begin
ShowMessage('Base created');
end;constructor TInherited.Create;
begin
inherited;
ShowMessage('Inherited created');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
a: TBase;
b, c: TInherited;
begin
b := TInherited.Create;
ShowAddress(b);
c := b.Create;
ShowAddress(b);
ShowAddress(c);
end;procedure TForm1.ShowAddress(o: TObject);
begin
ListBox1.Items.Add(IntToStr(Integer(o)));
end;end.
TInherited = class(TBase)
constructor Create; override;
end;
DWGZ你的意思我还不太明白,可以说明一下你的例子的含义么
var
a: TBase;
b: TInherited;
begin
b := TInherited.Create;
ShowAddress(b);
a = b as TBase;
a.Create; //虽然它在里只是简单执行Create 里面的代码,没有创建新的实例, 但是它
//执行的结果注意了,是 Inherited Create 而不是Base Created, 它实际上已
//已经实现多态, 为什么说无法实现多态呢;
ShowAddress(a);我个人认为这已经是多态了, 欢迎大家扔砖头
DWGZ的是说明通过重载和覆盖而实现类的多态。
基于以上原因我认为fs的解释比较贴切
好了给分咯