【问题标题】:Method Overloading is possible in objective c, am i right?在目标 c 中方法重载是可能的,对吗?
【发布时间】:2015-05-02 02:31:06
【问题描述】:

我到处都读到目标 c 不支持方法重载,但我遇到了不同的结果。 我对方法重载的了解是“方法名称相同但参数不同”。

请试试这个:

接口文件

-(void)methodoverloading;
-(void)methodoverloading :(int)parameter;

实现文件

-(void)methodoverloading{
    NSLog(@"methodoverloading  method with no Parameter");
}
-(void)methodoverloading :(int)parameter{
    NSLog(@"methodoverloading method with Parameter");
}

调用:

 [self methodoverloading];
 [self methodoverloading: 100];

结果:好的

2014-06-21 17:16:09.272 BasicFundamentals[869:a0b] methodoverloading method with no Parameter 2014-06-21 17:16:09.272 BasicFundamentals[869:a0b] methodoverloading method with Parameter

我在某处是对还是错?谢谢你

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    在 Objective C 中,方法的签名包括参数。

    你的两种方法:

    - (void)methodoverloading
    

    - (void)methodoverloading:(int)
    

    具有不同的签名(methodoverloadingmethodoverloading:),因此是不同的方法。

    人们说 Objective C 不支持重载的意思是你不能定义:

    - (void)method:(int)arg
    

    - (void)method:(NSString *)arg
    

    并让编译器根据您提供的类型在它们之间进行选择。

    【讨论】:

    • 是的,前两个方法的实际内部名称是methodoverloadingmethodoverloading:。如果您有两个参数,则名称将是 methodoverloading:anotherparm:。但是,正如您所指出的,parm 类型不是内部名称的一部分。
    • 谢谢萨皮先生。这就是我一直在寻找的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多