Delphi – 如果没有创建类,为什么这个函数有效?
发布时间:2020-12-15 09:48:37 所属栏目:大数据 来源:网络整理
导读:考虑这个课程: unit Unit2;interfacetype TTeste = class private texto: string; public function soma(a,b: integer): string; end;implementationprocedure TForm2.Button1Click(Sender: TObject);var teste: TTeste;begin teste:= nil; teste.texto:= '
考虑这个课程:
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崩溃了但功能没有,它是否像类功能一样工作? 解决方法
这是有效的,因为您没有尝试访问该类的任何字段.该功能不需要任何内存分配.如果在该函数中使用了字段texto,那么它会崩溃(正如您在其他测试中看到的那样),因为该内存未被解决.但在这里,没有涉及的记忆. a和b(以及该问题的函数结果)都分配在类之外的其他地方.实例化过程的一部分是为对象中的每个字段分配内存.
这只是巧合.实际上使用这样的东西仍然非常气馁.如果您觉得需要在没有实例化的情况下访问该函数,那么您应该将其设置为类函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |