2011-02-10 43 views
7

我對Objective-C方法重載有疑問。 Java支持方法重載與同名,不同類型參數的相同數量。但是當我嘗試在Objective-C中做類似的聲明時,它會拋出錯誤方法的重複聲明。考慮下面的代碼,Objective-C方法重載

/* Java */ 

int add(int i, int j); 
int add(int i, int j, int k); // Accepted 
float add(float i, float j); // Accepted 

/* Objective-C */ 

- (int)add:(int)i and:(int)j; 
- (int)add:(int)i and:(int)j and:(int)k; // Accepted 
- (float)add:(float)i and:(float)j; // Throws error 

爲什麼在Objective-C中不支持?有沒有替代方案?

+0

我對Objective-C中的方法重載也有疑問。我很確定它不存在。 – JeremyP 2011-02-10 08:44:50

+0

當然,這不是因爲你寫了'flat'而不是'float'? :P:P – hauntsaninja 2011-02-10 08:54:54

回答

15

它只是在Objective-C中不受支持。它在普通的舊C中不被支持,因此Objective-C同樣不會增加方法重載並不令人驚訝。爲了清楚起見,這有時候會很好。通常,解決此問題的方法是在函數名稱中包含有關參數的一些信息。例如:

- (int) addInt:(int)i toInt:(int)j; 
- (int) addInt:(int)i toInt:(int)j andInt:(int)k; 
- (float) addFloat:(float)i toFloat:(float)j; 
6

與此開始:

- (int)add:(int)i and:(int)j; 

這不會覆蓋任何東西 - 它只是另一種方法:

- (int)add:(int)i and:(int)j and:(int)k; // Accepted 

以下沒有特別因爲接受Objective-C不允許使用共變異體反變異體方法聲明。 Objective-C也沒有基於類型的調度重載la Java和C++。

- (float)add:(float)i and:(float)j; // Throws error 

請注意,Java直接從Objective-C派生而來。