Objective-C 中的函数重载?

Function Overloading in Objective-C?

C 专家根据我的理解 Objective-C 是一种动态绑定语言,不允许重载 class 中的任何方法。

但是有一件事让我很恼火,如果我写两个名称相同但参数列表数量不同的方法,例如:

 // Which is not allowed in objective-c

 -(void)updateValue:(int)intVal{

  } 

 -(void)updateValue:(float)floatVal{

  }

但是 Objective-C 允许的第二种情况是:

 // Allowed in Objective-C

 -(void)updateValue:(int)intVal{

   }

 -(void)updateValue:(float)floatVal :(int)intVal{

   }

虽然这两种情况都是方法重载。

现在我的问题是为什么允许第二种情况。

第二种情况下有两个参数的方法是否更改了方法名称?还是别的?

请解释一下。

Is the method with two params in the second case changing the Method Name ?

是的。方法名称是其所有参数前缀(包括冒号)的组合。所以你的两个方法是 updateValue:updateValue::.

HTH

-(void)updateValue:(int)intVal
  {
  } 

 -(void)updateValue:(float)floatVal
  {
  }

这是不允许的,因为当用户使用参数调用 updateValue 时,由于类型转换,值可能会更改,并且会显示不明确的方法。

 -(void)updateValue:(int)intVal
   {
   }

  -(void)updateValue:(float)floatVal :(int)intVal
  {
  }

是允许的,因为参数计数不同,因此编译器知道要调用哪个方法以及何时如此模棱两可的方法调用不是他们的