我是delphi的新手,我正在delphi 6中创建一个组件。但是我无法让构造函数运行:
unit MyComms1;
...
type
TMyComms = class(TComponent)
public
constructor MyConstructor;
end;
implementation
constructor TMyComms.MyConstructor;
begin
inherited;
ShowMessage('got here');
end;调用什么构造函数并不重要,但这段代码根本不运行构造函数。
编辑
根据请求,下面是如何初始化TMyComms类(此代码位于一个名为TestComms.pas的不同文件中):
unit TestComms;
interface
uses MyComms1, ...
type
TForm1 = class(TForm)
MyCommsHandle = TMyComms;
...
procedure BtnClick(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
procedure TForm1.BtnClick(Sender: TObject);
begin
MyCommsHandle.AnotherMyCommsProcedure;
end;编辑2
阅读一些答案--看起来像构造函数--必须在delphi中手动调用。这是对的吗?如果是这样的话,这肯定是我的主要错误--我习惯于php,每当将类分配给句柄时,就会自动调用__construct函数。
发布于 2013-06-03 05:14:38
您的代码不遵循Delphi命名准则--构造函数应该命名为Create。
由于您没有发布代码实际上调用了ctor,我想您可能根本没有调用它。尝试向窗体添加一个按钮,双击它并添加以下代码:
procedure TForm1.Button1Click(Sender : TObject)
var comms : TMyComms;
begin
comms := TMyComms.MyConstructor;
comms.Free;
end;顺便说一句,如果您是从TComponent派生的,那么您应该用一个参数覆盖构造函数--否则继承的方法可能不能正常工作。
interface
type TMyComms = class(TComponent)
private
protected
public
constructor Create(AOwner : TComponent); override;
end;
implementation
constructor TMyComms.Create(AOwner : TComponent)
begin
inherited Create(AOwner);
// Your stuff
end;
// Somewhere in code
var comms : TMyComms;
begin
comms := TMyComms.Create(nil);
end;发布于 2013-06-03 05:25:57
很可能不是调用TMyComms.MyConstructor来测试不寻常的调用和使用构造函数。用// **标记的方式将是最常见的。
type
TMyComms = class(TComponent)
public
constructor MyConstructor;
// the usual override;
// constructor Create(Owner:TComponent);override; // **
constructor Create(AOwner:TComponent);overload; override;
constructor Create(AOwner:TComponent;AnOtherParameter:Integer);overload;
end;
constructor TMyComms.Create(AOwner: TComponent);
begin
inherited ;
ShowMessage('got here Create');
end;
constructor TMyComms.Create(AOwner: TComponent; AnOtherParameter: Integer);
begin
inherited Create(AOwner);
ShowMessage(Format('got here Create with new parametere %d',[AnOtherParameter]));
end;
constructor TMyComms.MyConstructor;
begin
inherited Create(nil);
ShowMessage('got here MyConstructor');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TMyComms.MyConstructor.Free;
TMyComms.Create(self).Free;
TMyComms.Create(self,1234).Free;
end;发布于 2013-06-03 05:28:00
没有调用自定义构造函数,因为您没有调用它。
MyComm := TMyComms.MyConstructor;但是您的代码中也有错误。因为没有派生构造函数,所以可以使用简单的inherited继承。
type
TMyComms = class(TComponent)
public
constructor MyConstructor;
end;
implementation
constructor TMyComms.MyConstructor;
begin
inherited Create( nil ); // !
ShowMessage('got here');
end;如果自定义构造函数使用现有构造函数的相同名称和参数,则可以使用简单的inherited。
type
TMyComms = class(TComponent)
public
constructor Create( AOwner : TComponent ); override;
end;
implementation
constructor TMyComms.Create( AOwner : TComponent );
begin
inherited; // <- everything is fine
ShowMessage('got here');
end;https://stackoverflow.com/questions/16890343
复制相似问题