简体   繁体   English

Objective-C方法重载

[英]Objective-C Method Overloading

I am having doubt in Objective-C Method Overloading. 我对Objective-C方法重载有疑问。 Java supports method overloading with the same name , same number of arguments of different types . Java支持使用相同名称的方法重载,不同类型的相同数量的参数 But when I try to do similar declaration in Objective-C, it throws me the error Duplicate declaration of method . 但是当我尝试在Objective-C中做类似的声明时,它会抛出错误重复声明方法 Consider the following code, 考虑以下代码,

/* 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

Why is this not supported in Objective-C? 为什么Objective-C不支持这个? Is there an alternative for this? 有替代方案吗?

It simply isn't supported in Objective-C. Objective-C不支持它。 It wasn't supported in plain old C, so it isn't all that surprising that Objective-C likewise did not add method overloading. 普通的旧C不支持它,因此Objective-C同样没有添加方法重载也不足为奇。 For clarity, this can sometimes be good. 为清楚起见,这有时可能是好的。 Typically, the way around this is to include some information about the parameter in the function name. 通常,解决此问题的方法是在函数名称中包含有关参数的一些信息。 Ex: 例如:

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

Starting with this: 从这开始:

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

This does not override anything -- it is just another method: 这不会覆盖任何东西 - 它只是另一种方法:

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

The following isn't accepted specifically because Objective-C does not allow for co-variant or contra-variant method declarations. 以下内容未被特别接受,因为Objective-C不允许共变反变方法声明。 Nor does Objective-C do type based dispatch overloading a la Java and C++. Objective-C也没有基于类型的调度重载Java和C ++。

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

Note that Java was derived quite directly from Objective-C. 请注意,Java是直接从Objective-C派生的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM