Delphi-如果未创建类,此功能为何起作用? [英] Delphi - why does this function work if the class is not created?

查看:42
本文介绍了Delphi-如果未创建类,此功能为何起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此类:

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.

它真的可以工作吗?为什么? var崩溃了,但函数没有崩溃,它像类的功能一样工作吗?

should it really work? why? the var crashed but the function doesnt, does it works like a class funtion?

推荐答案

这是有效的,因为您没有尝试访问该类的任何字段。该功能不需要任何内存分配。如果在该函数中使用了 texto 字段,则该字段将崩溃(如您在其他测试中所见),因为该内存没有得到解决。但是在这里,不涉及内存。 a b (以及该函数的功能结果)都分配在该类之外的其他位置。实例化过程的一部分是为对象中的每个字段分配内存。

This works because you are not attempting to access any fields of the class. The function doesn't require any memory allocation. If the field texto was used in that function, then it would crash (as you see in your other test), because that memory isn't addressed. But here, there is no memory involved. Both a and b (and the function result for that matter) are allocated elsewhere outside of the class. Part of the instantiation process is allocating memory for each and every one of the fields in the object.

这只是巧合。仍然不鼓励您实际使用这种方法。如果您需要无需实例化即可访问该函数,则应将其设为类函数。

This is just coincidental. It's still highly discouraged to actually use something like this. If you feel the need to access the function without instantiation, then you should make it a class function instead.

这篇关于Delphi-如果未创建类,此功能为何起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆