开发者

Objective-C Method Overloading

I am having doubt in Objective-C Method Overloading. Java supports method overloadi开发者_StackOverflowng with the same name, same number of arguments of different types. But when I try to do similar declaration in Objective-C, it throws me the error Duplicate declaration of method. 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? Is there an alternative for this?


It simply isn't supported in 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. 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. Nor does Objective-C do type based dispatch overloading a la Java and C++.

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

Note that Java was derived quite directly from Objective-C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜