objective-c - Objective-c的复合疑问
漂亮男人
漂亮男人 2017-05-02 09:27:46
0
1
532
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;
}
漂亮男人
漂亮男人

全部回复(1)
过去多啦不再A梦

rect 又不是成员变量,而且你又注掉了Rectangle *rect = [[Rectangle alloc] initWithWidth:s Height:s]; 当然打不出了[sq area]和[sq perimeter]

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板