标签:objective-c 继承
这第4篇内容比较少,主要说的是obj-c中的类的继承,需要说明的是我只是写了继承中最简单的形式,如果全部展开来说,那就多了去了!关键是现在肚子里还没装够墨水,没法展开啊!
下面的代码中,我们写了2个类:父类A和子类B,然后B中对A中的方法做了重写。
#import <Foundation/Foundation.h> @interface A:NSObject{ int i; } @property int i; -(void)print; @end @implementation A @synthesize i; -(void)print{ NSLog(@"[class A][i:%d]:hello!",i); } @end @interface B:A{ int j; } @property int j; @end @implementation B @synthesize j; -(void)print{ NSLog(@"[class B:A][i:%d,j:%d]hello!",i,j); } @end int main(int argc,char *argv[]) { @autoreleasepool{ NSLog(@"hello obj-c!"); A *a = [[A alloc] init]; B *b = [[B alloc] init]; a.i = 101; b.i = 1001; b.j = 1002; [a print]; [b print]; } return 0; }
apple@kissAir: objc_src$clang -fobjc-arc -framework Foundation 1.m -o 1
apple@kissAir: objc_src$./1
2014-06-29 10:34:30.547 1[1035:507] hello obj-c!
2014-06-29 10:34:30.549 1[1035:507] [class A][i:101]:hello!
2014-06-29 10:34:30.549 1[1035:507] [class B:A][i:1001,j:1002]hello!
好,下面我们稍微修改一下class A中实例变量i的定义,使它成为私有,即不在@interface中定义而在@implementation中定义i。这时编译时会发现class B中print会报错:
apple@kissAir: objc_src$clang -fobjc-arc -framework Foundation 1.m -o 1
1.m:34:41: error: instance variable ‘i‘ is private
NSLog(@"[class B:A][i:%d,j:%d]hello!",i,j);
改正也很简单呢,直接 self.i即可,下面是修改后的完整代码:
#import <Foundation/Foundation.h> @interface A:NSObject @property int i; -(void)set_i:(int)i; -(void)print; @end @implementation A{ int i; } @synthesize i; -(void)set_i:(int)i_v{ i = i_v; } -(void)print{ NSLog(@"[class A][i:%d]:hello!",i); } @end @interface B:A{ int j; } @property int j; @end @implementation B @synthesize j; -(void)print{ NSLog(@"[class B:A][i:%d,j:%d]hello!",self.i,j); } @end int main(int argc,char *argv[]) { @autoreleasepool{ NSLog(@"hello obj-c!"); A *a = [[A alloc] init]; B *b = [[B alloc] init]; //a.i = 101; //b.i = 1001; [a set_i:99]; [b set_i:199]; b.j = 1002; [a print]; [b print]; } return 0; }
标签:objective-c 继承
原文地址:http://blog.csdn.net/mydo/article/details/35779637