1、 繼承的文法如下:
@interface TestCoop : NSObject {
int iMonth;
int iYear;
int iDay;
}
- (void) setYear: (int) iYear;
- (void) primalSetData: (int)iYear :(int)iMonth :(int)iDay;
- (void) setData: (int)Year iMonth:(int)iMonth iDay:(int)iDay;
- (void) displayDateInfo;
@end
@interface TestAddWeather : TestCoop{
NSString *pstrWeather;
}
- (void) setWeather: (NSString *) pstrWeather;
- (void) displayDateInfo;
@end
@end
2、不過Objective-C不支援多繼承,類似如下寫法
@interface TestAddWeather : TestCoop, PrintableObect
編譯會報錯的,不過Objective-C的其他特性可以滿足多繼承的功能,以後再研究
基本的繼承文法和多態也和C++差不多,看實現代碼:
@implementation TestCoop
- (void) displayDateInfo{
NSLog(@"Today is: %d.%d.%d/n", iYear, iMonth, iDay);
}
- (void) setYear: (int) year{
iYear = year;
}
- (void) primalSetData: (int)year :(int)month :(int)day{
iYear = year;
iMonth = month;
iDay = day;
}
- (void) setData: (int)year iMonth:(int)month iDay:(int)day{
iYear = year;
iMonth = month;
iDay = day;
}
@end
@implementation TestAddWeather
- (void) setWeather: (NSString *) pWeather{
[pstrWeather release];
pstrWeather = nil;
pstrWeather = [[NSString alloc] initWithString:pWeather];
}
- (void) displayDateInfo{
NSLog(@"Today is: %d.%d.%d,weather: %@/n", iYear, iMonth, iDay, pstrWeather);
}
@end
測試代碼:
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
//NSLog(@"%d-,%s %@/n", 12, "hel123lo", @"123");
TestCoop *ptest = [[TestCoop alloc] init];
[ptest primalSetData :2009 :03 :05];
[ptest displayDateInfo];
[ptest setData:2010 iMonth:06 iDay:06];
[ptest displayDateInfo];
[ptest setYear:1987];
[ptest displayDateInfo];
[ptest release];
TestAddWeather *ptestweather = [[TestAddWeather alloc] init];
[ptestweather setData:2010 iMonth:03 iDay:05];
[ptestweather setWeather:@"Rainy"];
[ptestweather displayDateInfo];
[ptestweather setWeather:@"Cloudy"];
[ptestweather displayDateInfo];
[ptestweather release];
[pool drain];
return 0;
}
列印出如下資訊:
Today is: 2009.3.5
Today is: 2010.6.6
Today is: 1987.6.6
Today is: 2010.3.5,weather: Rainy
Today is: 2010.3.5,weather: Cloudy
如果要調用父類的函數,可以在定義函數的時候使用super
關鍵字
比如:
@implementation TestAddWeather
- (void) setWeather: (NSString *) pWeather{
[pstrWeather release];
pstrWeather = nil;
pstrWeather = [[NSString alloc] initWithString:pWeather];
[super setYear:2009];
}
3.組合也和C++差不多,而且為了防止標頭檔重複引用,有和C++一樣的用法
當該類成員只通過其他類的指標訪問時,可以標頭檔中不import,只聲明
@class TestAddWeather;
如下
然後在.m/.mm檔案中import “TestAddWeather.h”,防止標頭檔依賴關係過多導致編譯變慢