我正在使用Borland Delphi7进行Pascal编程。我下载了一个相当基本(也是免费的)的复杂数学函数源代码库,但不幸的是它并没有带有任何用法示例。由于我不太熟悉Pascal中的类,我认为我只需要一个简单的用法示例来让我入门。
任何示例都可以,即使是将两个数字相加的示例也可以让我入门。以下是我的尝试(非常糟糕)。我认为我的问题在于我不知道如何使用类构造函数。
任何示例都可以,即使是将两个数字相加的示例也可以让我入门。以下是我的尝试(非常糟糕)。我认为我的问题在于我不知道如何使用类构造函数。
uses ComplexMath in 'complexmath.pas'
var z1,z2,z3 : TComplexNumber;
begin
z1.R:=1.0; z1.I:=2.0;
z2.R:=3.0; z2.I:=-1.0;
z3 := TComplexMath.Add(z1,z2);
end.
TComplexMath的完整源代码可以在此处获取:http://delphi.about.com/library/weekly/aa070103a.htm。我还将部分源代码剪切并粘贴在下面(请注意,该代码是完整文件,除了我明确指出已经被剪切的部分)。
TComplexMath部分源代码清单如下:
unit ComplexMath;
interface
uses Windows, SysUtils, Classes, Controls, Math;
type
TComplexNumber = record
R : single;
I : single;
end;
TComplexMath = class(TComponent)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
function Add(C1, C2 : TComplexNumber) : TComplexNumber; overload;
{ Returns the complex sum of C1 and C2 }
function Add(C1, C2, C3 : TComplexNumber) : TComplexNumber; overload;
{ Returns the complex sum of C1 and C2 and C3 }
... and a bunch more like this ...
implementation
procedure Register;
begin
RegisterComponents('delphi.about.com', [TComplexMath]);
end;
constructor TComplexMath.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
end;
function TComplexMath.Add(C1, C2 : TComplexNumber) : TComplexNumber;
begin
Result.R := C1.R + C2.R;
Result.I := C1.I + C2.I;
end;
... and a bunch more like this ...
end.
在经过一段时间的努力后,我最终剥离了类定义,并仅使用函数本身(就像简单的函数库)。虽然这对我有用,但我知道这不是此组件的预期使用方式。如果有人能向我展示如何按照原意简单地使用此类的例子,我将不胜感激。
nil
也可以。什么是“owner”?当所有者被释放时,它所拥有的东西也会被释放。self
表示类的当前实例,仅存在于方法中。因此,例如,如果您有一个表单和一个按钮,并双击该按钮,则会进入像procedure TForm1.Button1Click(...
这样的方法,然后self
将引用TForm1
的当前实例,可能是Form1
。但在这种情况下,所有者没有用于任何事情,因此您指定什么并不重要(除非您销毁它)。因此,nil
(表示“没有所有者”)完全可以。 - Andreas RejbrandSelf
在当前行不可用,因为当前行不在方法内(即不属于类的函数或过程,与当前实例一起工作)。 - Andreas RejbrandSelf
没有被定义,因为你的代码不在一个方法内。 - David Heffernan