跳轉到內容

Ada 程式設計/函式過載

來自華夏公益教科書,自由的教科書

Ada. Time-tested, safe and secure.
Ada。經時間考驗,安全可靠。

函式過載(也稱方法過載)是一種程式設計概念,允許程式設計師定義兩個或多個具有相同名稱並在相同範圍內的函式。

每個函式都有一個唯一的簽名(或標頭檔案),它源自

  1. 函式/過程名稱
  2. 引數數量
  3. 引數型別
  4. 引數順序
  5. 引數名稱
  6. 返回值型別

請注意:並非所有上述簽名選項在所有程式語言中都可用。

可用的函式過載
語言 1 2 3 4 5 6
Ada
C++
Java
Swift

警告:函式過載經常與函式重寫混淆。在函式過載中,建立了一個具有不同簽名的函式,新增到可用函式池中。然而,在函式重寫中,聲明瞭一個具有相同簽名的函式,替換了新函式上下文中的舊函式。

由於函式名稱在這種情況下相同,我們必須透過更改引數列表(最後三個外星人)中的某些內容來保留簽名的唯一性。

如果函式的簽名足夠不同,編譯器可以區分在每次出現時要使用哪個函式。這個搜尋適當函式的過程稱為函式解析,它可能相當密集,尤其是在有很多同名函式的情況下。

支援隱式型別約定的程式語言通常在沒有完全匹配的函式時使用引數提升(即整數到浮點數的型別轉換)。引數降級很少使用。

當兩個或多個函式匹配函式解析過程中的條件時,編譯器會報告歧義錯誤。透過編輯原始碼(例如使用型別轉換)為編譯器新增更多資訊,可以解決此類疑慮。

示例程式碼展示瞭如何使用函式過載。由於函式實際上執行相同的操作,因此使用函式過載是有意義的。

檔案:function_overloading.adb (檢視純文字下載頁面瀏覽所有)
function Generate_Number (MaxValue : Integer) return Integer is
   subtype Random_Type is Integer range 0 .. MaxValue;
   package Random_Pack is new Ada.Numerics.Discrete_Random (Random_Type);
 
   G : Random_Pack.Generator;
begin
   Random_Pack.Reset (G);
   return Random_Pack.Random (G);
end Generate_Number;


function Generate_Number (MinValue : Integer;
                          MaxValue : Integer) return Integer
is
   subtype Random_Type is Integer range MinValue .. MaxValue;
   package Random_Pack is new Ada.Numerics.Discrete_Random (Random_Type);
 
   G : Random_Pack.Generator;
begin
   Random_Pack.Reset (G);
   return Random_Pack.Random (G);
end Generate_Number;

呼叫第一個函式

[編輯 | 編輯原始碼]

第一個程式碼塊將生成從 0 到指定引數MaxValue的數字。適當的函式呼叫是

 Number_1 : Integer := Generate_Number (10);

呼叫第二個函式

[編輯 | 編輯原始碼]

第二個需要另一個引數MinValue。函式將返回大於或等於MinValue且小於MaxValue的數字。

 Number_2 : Integer := Generate_Number (6, 10);

Ada 中的函式過載

[編輯 | 編輯原始碼]

Ada 支援所有六個簽名選項,但是如果您使用引數名稱作為選項,則在呼叫函式時始終必須命名引數。即

Number_2 : Integer := Generate_Number (MinValue => 6,
                                       MaxValue => 10);

請注意,您不能在同一個包中過載泛型過程或泛型函式。以下示例將無法編譯

 package myPackage
   generic
     type Value_Type is (<>);  
   -- The first declaration of a generic subprogram
   -- with the name "Generic_Subprogram"
   procedure Generic_Subprogram (Value : in out Value_Type);
   ...
   generic
     type Value_Type is (<>); 
   -- This subprogram has the same name, but no
   -- input or output parameters. A non-generic
   -- procedure would be overloaded here.
   -- Since this procedure is generic, overloading
   -- is not allowed and this package will not compile.
   procedure Generic_Subprogram;
   ...
   generic
     type Value_Type is (<>); 
   -- The same situation.
   -- Even though this is a function and not
   -- a procedure, generic overloading of
   -- the name "Generic_Subprogram" is not allowed.
   function Generic_Subprogram (Value : Value_Type) return Value_Type;
 end myPackage;

華夏公益教科書

[編輯 | 編輯原始碼]

Ada 95 參考手冊

[編輯 | 編輯原始碼]

Ada 2005 參考手冊

[編輯 | 編輯原始碼]
華夏公益教科書