嗨,我是一個新手,以客觀-C,今天我學習動態類型的概念,並結合,一切都很好,直到我寫和執行該程序爲什麼具有相同名稱(屬於不同類)的兩個方法在使用動態類型和動態綁定時應該具有相同的原型?
#import <Foundation/Foundation.h>
@interface A:NSObject
@property int var;
-(int)add:(A*)argObj;
@end
@implementation A
@synthesize var;
-(int)add:(A *)argObj
{
return (self.var + argObj.var);
}
@end
@interface B:NSObject
@property double var1;
-(double)add:(B *)argObj;
@end
@implementation B
@synthesize var1;
-(double)add:(B *)argObj
{
return (self.var1 + argObj.var1);
}
@end
int main()
{
@autorleaease{
id data1, data2;
A * aobj1 = [[A alloc]init];
aobj1.var = 30;
A * aobj2 = [[A alloc]init];
aobj2.var = 50;
data1 = aobj1;
data2 = aobj2;
NSLog(@"The sum of two A objs is : %i",[data1 add: data2]);// prints 80 which is correct
B * bobj1 = [[B alloc]init];
bobj1.var1 = 5.5;
B * bobj2 = [[B alloc]init];
bobj2.var1 = 5.5;
data1 = bobj1;
data2 = bobj2;
NSLog(@"The sum of 2 B objs is : %f",[data1 add: data2]);// prints 0.0000 why so ????
}
return 0;
}
我得到的輸出,當我執行加方法,但是當我在類BI上執行add方法時得到了錯誤的答案。爲什麼是這樣??
這就是我的輸出。在輸出編譯器警告我這樣
main.m: In function 'main':
main.m:47:5: warning: multiple methods named '-add:' found [enabled by default]
NSLog(@"The sum of two A objs is : %i",[data1 add: data2]);
^
main.m:8:1: note: using '-(int)add:(A *)argObj'
-(int)add:(A*)argObj;
^
main.m:8:1: note: also found '-(int)add:(A *)argObj'
main.m:26:1: note: also found '-(double)add:(B *)argObj'
-(double)add:(B *)argObj;
^
main.m:55:5: warning: multiple methods named '-add:' found [enabled by default]
NSLog(@"The sum of 2 B objs is : %f",[data1 add: data2]);
^
main.m:8:1: note: using '-(int)add:(A *)argObj'
-(int)add:(A*)argObj;
^
main.m:8:1: note: also found '-(int)add:(A *)argObj'
main.m:26:1: note: also found '-(double)add:(B *)argObj'
-(double)add:(B *)argObj;
^
Executing the program....
$demo
2014-01-20 04:06:05.788 demo[30357] The sum of two A objs is : 80
2014-01-20 04:06:05.789 demo[30357] The sum of 2 B objs is : 0.000000
編譯器在說多種方式存在,但這些方法是完全屬於不同的類,雖然我們使用動態類型和動態綁定呼叫將得到解決正確的權利??那麼爲什麼我會得到這樣的輸出?在此先感謝.. :)
爲什麼使用'id data1,data2'而不是實際的對象? – trojanfoe
雅我已經做到了,但因爲我是學動態類型和有約束力的,我想利用這裏這些概念我的意思是我想要的調用方法在運行期間得到解決。 – iamyogish