如何让函数的变量参能够接受相容但不同的实参? (100分)

  • 主题发起人 fatalexception
  • 开始时间
F

fatalexception

Unregistered / Unconfirmed
GUEST, unregistred user!
一个函数,打算用窗体做参数,并且必须是变量参(不能是值参):
///////////////////////////////////////////////////
function F(var TheForm: TForm):Boolean;
begin
Do something....
TheForm:=XXXXXXXX;
Result:=True;
end;
/////////////////////////////////////////////////////

调用时,实参可以是任何从TForm派生出来的Form,例如:
////////////////////////////////////////////////////
Program Login;
Type
TfrmLogin=Class of TForm;
Var
frmLogin:TfrmLogin;
Begin
F(frmLogin);
end.
//////////////////////////////////////////////

怎样才能让变量参接受不同类型但有派生关系的实参呢?(不用指针)
谢谢!
 
如果传入参数是它的SubClass,可用Tform(VarName)将参数传入
 
首先,你有一个认识上的错误,值参和形参多用于简单类型和复合类型的变量,如果你的参数传递的是类,
它本身就不需要什么变量参数,因为类的实例实际上是一个指针,而传指针就是传可变传参,
你的函数体内改变类实例的属性后完全可以回传.

另外:
Type
TfrmLogin=Class of TForm;

Type
TfrmLogin=Class(TForm);
是完全不同的一回事;
后者才是指从TForm上继承,前者是指类的类型,比较难理解,请他看下面的Help!


A constructor can be called using a variable of a class-reference type. This allows construction of objects whose type isn抰 known at compile time. For example,

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;

The CreateControl function requires a class-reference parameter to tell it what kind of control to create. It uses this parameter to call the class抯 constructor. Because class-type identifiers denote class-reference values, a call to CreateControl can specify the identifier of the class to create an instance of. For example,

CreateControl(TEdit, 'Edit1', 10, 10, 100, 20);

Constructors called using class references are usually virtual. The constructor implementation activated by the call depends on the runtime type of the class reference.
 
谢谢二位,我补充一下:我需要在函数中动态创建这个窗体,并将窗体变量赋值。例如这样
调用函数:
CreateForm(frmLogin);
函数定义形如:
function CreateForm(var FormVar:TForm):Boolean;
begin
Result:=True;
Try
FormVar:=TXXXX.Create(nil);
Except
Result:=False;
End;
end;
我不但要在函数内引用窗体对象的属性和方法,还要先创建它,并给窗体变量赋值。
不知道这次说明白没有,请指教!
 
我按照svw0506的方法试通过了。
 
多人接受答案了。
 
顶部