Hen*_*ria 5 delphi class function
考虑这个课程:
unit Unit2;
interface
type
TTeste = class
private
texto: string;
public
function soma(a, b: integer): string;
end;
implementation
procedure TForm2.Button1Click(Sender: TObject);
var
teste: TTeste;
begin
teste:= nil;
teste.texto:= '';//access violation
showmessage(teste.soma(5, 3));//no access violation
end;
{ TTeste }
function TTeste.soma(a, b: integer): string;
begin
result:= (a+b).ToString;
end;
end.
Run Code Online (Sandbox Code Playgroud)
它真的有效吗?为什么?var崩溃了但功能没有,它是否像类功能一样工作?
Jer*_*dge 13
这是有效的,因为您没有尝试访问该类的任何字段.该功能不需要任何内存分配.如果texto
在该函数中使用该字段,那么它将崩溃(正如您在其他测试中看到的那样),因为该内存未被解决.但在这里,没有涉及的记忆.两者a
和b
(以及该问题的函数结果)都分配在类之外的其他地方.实例化过程的一部分是为对象中的每个字段分配内存.
这只是巧合.实际上使用这样的东西仍然非常气馁.如果您觉得需要在没有实例化的情况下访问该函数,那么您应该将其设置为类函数.