簡體   English   中英

Delphi - 如果沒有創建類,為什么這個函數有效?

[英]Delphi - why does this function work if the class is not created?

考慮這個課程:

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 ,那么它會崩潰(正如您在其他測試中看到的那樣),因為該內存未被解決。 但在這里,沒有涉及的記憶。 ab (以及該問題的函數結果)都分配在類之外的其他地方。 實例化過程的一部分是為對象中的每個字段分配內存。

這只是巧合。 實際上使用這樣的東西仍然非常氣餒。 如果您覺得需要在沒有實例化的情況下訪問該函數,那么您應該將其設置為類函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM