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”,防止头文件依赖关系过多导致编译变慢