objective-c inherit

来源:互联网 发布:cae有限元分析软件 编辑:程序博客网 时间:2024/06/06 17:44
#import <Foundation/Foundation.h>@interface Shape:NSObject{    double width;    double height;}-(id)init:(double)_w:(double)_h;-(double)area;@end
#import "Shape.h"@implementation Shape-(id)init:(double)_w:(double)_h{    self = [super init];    if(self){        self->width = _w;        self->height = _h;    }    return self;}-(double)area{    return width*height;}@end

#import "Shape.h"@interface Circle:Shape{    double r;}-(id)init:(double)_r;-(void)setR:(double)_r;@end

#import "Circle.h"@implementation Circle-(id)init:(double)_r{    self = [super init:1:1];    if(self){        self->r = _r;    }    return self;    }-(double)area{        return 3.14*r*r;    }-(void)setR:(double)_r{        r = _r;    }@end
#import <Foundation/Foundation.h>#import "Circle.h"int main (int argc, const char * argv[]){   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];   NSLog (@"hello world");   Shape *s = [Shape alloc];   [s init:1.3:4.6];   NSLog(@"%lf",[s area]);      Circle *c = [Circle alloc];   [c init:5.5];   NSLog(@"%lf",[c area]);      Shape *sc = c;   NSLog(@"%lf",[sc area]);      c.r = 100;   NSLog(@"%lf",[c area]);      //sc.r = 99;   NSLog(@"%lf",[sc area]);         [pool drain];   return 0;}

sh-4.3$ gcc `gnustep-config --objc-flags` -L/usr/GNUstep/System/Library/Libraries -lgnustep-base -lobjc *.m -o main                                                sh-4.3$ main                                                                                                                                                       2016-04-04 04:36:47.974 main[373] hello world                                                                                                                      2016-04-04 04:36:47.974 main[373] 5.980000                                                                                                                         2016-04-04 04:36:47.975 main[373] 94.985000                                                                                                                        2016-04-04 04:36:47.975 main[373] 94.985000                                                                                                                        2016-04-04 04:36:47.975 main[373] 31400.000000                                                                                                                     2016-04-04 04:36:47.975 main[373] 31400.000000  



0 0
原创粉丝点击