考虑这个类:
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
and b
(以及与此相关的函数结果)被分配在类之外的其他地方。实例化过程的一部分是为对象中的每个字段分配内存。
这只是巧合。仍然非常不鼓励实际使用这样的东西。如果您觉得需要在不实例化的情况下访问该函数,那么您应该将其设为类函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)