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;
}
@end
Square
#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];
}
@end
main()函数
#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;
}
过去多啦不再A梦2017-05-02 09:29:46
rect is not a member variable, and you checked out Rectangle *rect = [[Rectangle alloc] initWithWidth:s Height:s]; Of course, [sq area] and [sq perimeter] cannot be typed