#import <Foundation/Foundation.h>
@interface Rectangle : NSObject {
int width;
int height;
}
@property int width, height;
-(void) setWidth: (int) w andHeight: (int) h;
-(int) area;
-(int) perimeter;
-(Rectangle *) initWithWidth: (int) w andHeight: (int) h;
@end
Rectangle.m:
#import "Rectangle.h"
@implementation Rectangle
@synthesize width, height;
-(void) setWidth: (int) w andHeight: (int) h{
width=w;
height=h;
}
-(int) area{
return width * height;
}
-(int) perimeter{
return 2*width+2*height;
}
-(Rectangle *) initWithWidth: (int) w andHeight: (int) h{
self = [super init];
if (self)
[self setWidth:w andHeight:h];
return self;
}
@end
#import "Rectangle.h"
@interface Square : Rectangle
-(void) setSide:(int)s;
-(int) side;
-(Square *)initWithSide: (int) s;
@end
#import "Square.h"
@implementation Square
-(void) setSide: (int) s{
[self setWidth:s andHeight:s];
}
-(int) side{
return width;
}
-(Square *)initWithSide: (int) s{
self=[super init];
if (self)
[self setSide:s];
return self;
}
@end
主程式:
#import <Foundation/Foundation.h>
#import "Square.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Rectangle *myRect = [[Rectangle alloc] initWithWidth:5 andHeight:8];
Square *mySquare = [[Square alloc] initWithSide:5];
NSLog(@"長方型w=%i,h=%i", myRect.width, myRect.height);
NSLog(@"長方型面積Area = %i, 週長Perimeter = %i",[myRect area],[myRect perimeter]);
NSLog(@"正方型邊長s=%i", [mySquare side]);
NSLog(@"正方型面積Area = %i, 週長Perimeter = %i",[mySquare area],[mySquare perimeter]);
[myRect release];
[pool drain];
return 0;
}
長方型w=5,h=8
長方型面積Area = 40, 週長Perimeter = 26
正方型邊長s=5
正方型面積Area = 25, 週長Perimeter = 20
限會員,要發表迴響,請先登入