合成对象

作者:追风剑情 发布于:2019-2-26 11:25 分类:Objective-C

示例:合成对象

Rectangle.h、Rectangle.m

参见 http://www.devacg.com/?post=925

Square.h

#import "Rectangle.h"

//采用合成对象来重新实现Square
@interface Square : NSObject
{
    Rectangle *rect;
}

-(void) setSide: (int) s;
-(int) side;
-(int) area;
-(int) perimeter;

@end


Square.m

#import "Square.h"

@implementation Square

// 重载初始化方法
-(instancetype) init
{
    self = [super init];
    if (self) {
        //通过重载初始化方法来给rect赋值
        rect = [[Rectangle alloc] init];
    }
    return self;
}

// 设置边长
-(void) setSide: (int) s
{
    [rect setWidth: s andHeight: s];
}

-(int) side
{
    return rect.width;
}

// 求面积
-(int) area
{
    return rect.width * rect.width;
}

// 求周长
-(int) perimeter
{
    return rect.width * 4;
}

@end


main.m

#import <Foundation/Foundation.h>
#import "Square.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Square *square = [[Square alloc] init];
        
        [square setSide: 10];
        NSLog(@"area: %i, perimeter: %i",
              [square area], [square perimeter]);
    }
    return 0;
}

运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号