问题描述
1.这个例子是objective-c程序设计 11章的合成对象的练习2.程序没有报错,但提示有个实例变量没有使用3.mian()程序中打印的数字不正确,不知道哪里出了问题!!代码:Rectangle#import <Foundation/Foundation.h>@interface Rectangle : NSObject@property int width,height;-(instancetype) initWithWidth:(int) w Height:(int) h;-(int) area;-(int) primeter;@end#import 'Rectangle.h'@implementation Rectangle@synthesize width,height;-(instancetype) initWithWidth:(int)w Height:(int)h{if (self = [super init]) {width = w;height= h; }return self;}-(int) area{ return width*height;}-(int) primeter{ return (width+height)*2;}@endSquare#import <Foundation/Foundation.h>#import 'Rectangle.h'@interface Square : NSObject{ Rectangle *rect;}@property int Side;-(instancetype) initWithSide:(int) s;-(void) setSide:(int) s;-(int) Side;-(int) area;-(int) perimeter;@end#import 'Square.h'@implementation Square@synthesize Side;-(instancetype) init{if (self = [super init]) {self = [[Square alloc] initWithSide:0]; }return self ;}-(instancetype) initWithSide:(int)s{ if (self = [super init]){//Rectangle *rect = [[Rectangle alloc] initWithWidth:s Height:s]; [rect initWithWidth:s Height:s]; }return self;}-(void) setSide:(int)s{ Side = s;}-(int) Side{ return Side;}-(int) area{ return [rect area];}-(int) perimeter{ return [rect primeter];}@endmain()函数#import <Foundation/Foundation.h>#import 'Square.h'#import 'Rectangle.h'int main(int argc, const char * argv[]) { @autoreleasepool {Square *sq = [[Square alloc] initWithSide:50];NSLog(@'正方形的边长%i',[sq area]);NSLog(@'正方形的面积%i',[sq perimeter]); } return 0;}
问题解答
回答1:rect 又不是成员变量,而且你又注掉了Rectangle *rect = [[Rectangle alloc] initWithWidth:s Height:s]; 当然打不出了[sq area]和[sq perimeter]