type
TRec = record
Line1: Integer;
Line2: Integer;
end;
PRec = ^TRec;
//两种方法
...
function GetRec: PRec;
begin
Result := nil;
if True then
New(PRec);//要不要呢,我是认为应该要,但是如果要,由谁去释放?
Result.Line1 = 1;
Result.Line2 = 2;
end;
end;function GetRec: TRec;
begin
//Result := nil;这样我就无法返回空值了
if True then
Result.Line1 = 1;
Result.Line2 = 2;
end;
end;
TRec = record
Line1: Integer;
Line2: Integer;
end;
PRec = ^TRec;
//两种方法
...
function GetRec: PRec;
begin
Result := nil;
if True then
New(PRec);//要不要呢,我是认为应该要,但是如果要,由谁去释放?
Result.Line1 = 1;
Result.Line2 = 2;
end;
end;function GetRec: TRec;
begin
//Result := nil;这样我就无法返回空值了
if True then
Result.Line1 = 1;
Result.Line2 = 2;
end;
end;
begin
//Result := nil;这样我就无法返回空值了
if True then
Result.Line1 = 1;
Result.Line2 = 2;
end;
end;
如果想表示一个错误,可以用raise Exception.Create('error');
begin
if r = nil then exit;
R^.Line1 = 1;
R^.Line2 = 2;
end;
我经常这样做,一般向函数传指针类型的(包括Object)参数,在调用的环境中创建和释放,不在函数中创建或释放。
TMan = record
ID: Integer;
Name: string;
Age: Intege;
end
PMan = ^TMan;function GetMan(ID: Integer): PMan
begin
if 找到 then
begin
Result.ID := xx;
Result.Name := xx;
Result.Age := xx;
end
else begin
Result := nil;//这肯定是不行的,我想这样写Result.ID = -1,但总觉得不好
end;
end;function GetMain(ID: Integer): TMan
begin
if 找到 then
begin
Result.ID := xx;
Result.Name := xx;
Result.Age := xx;
end
else begin
Result.ID = -1;
end;
end;
end;
如果找到了我就回
function GetMan(ID: Integer): PMan
begin
if 找到 then
begin
Result.ID := xx;
Result.Name := xx;
Result.Age := xx;
end
else begin
Result := nil;
end;
end;function GetMain(ID: Integer): TMan
begin
if 找到 then
begin
Result.ID := xx;
Result.Name := xx;
Result.Age := xx;
end
else begin
Result.ID = nil;;//这肯定是不行的,我想这样写Result.ID = -1,但总觉得不好
end;
end;
if true thenend;
那个Begin 去哪了?你这个程序能编译吗?
另外你调用 Result.line1:=1 ;这个Result是一个指针,它指向谁呢?你这样写不报错才怪呢?
正确的写法应该是:
function GetRec: TRec;
begin
New(Result); //分配内存
if assigned(Result) then //如果分配成功
begin
Result.Line1 = 1; //向着两个赋值;
Result.Line2 = 2;
end;
end;
释放应该由调用该程序的负责。
如
P:=GetRec;
.....//对P的使用。
dispose(P);//这句话就完成了对 GetRec中分配内存的释放(这句一定要,否则
// 返回值false/true...