合成对象

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

示例:合成对象

Rectangle.h、Rectangle.m

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

Square.h

  1. #import "Rectangle.h"
  2.  
  3. //采用合成对象来重新实现Square
  4. @interface Square : NSObject
  5. {
  6. Rectangle *rect;
  7. }
  8.  
  9. -(void) setSide: (int) s;
  10. -(int) side;
  11. -(int) area;
  12. -(int) perimeter;
  13.  
  14. @end


Square.m

  1. #import "Square.h"
  2.  
  3. @implementation Square
  4.  
  5. // 重载初始化方法
  6. -(instancetype) init
  7. {
  8. self = [super init];
  9. if (self) {
  10. //通过重载初始化方法来给rect赋值
  11. rect = [[Rectangle alloc] init];
  12. }
  13. return self;
  14. }
  15.  
  16. // 设置边长
  17. -(void) setSide: (int) s
  18. {
  19. [rect setWidth: s andHeight: s];
  20. }
  21.  
  22. -(int) side
  23. {
  24. return rect.width;
  25. }
  26.  
  27. // 求面积
  28. -(int) area
  29. {
  30. return rect.width * rect.width;
  31. }
  32.  
  33. // 求周长
  34. -(int) perimeter
  35. {
  36. return rect.width * 4;
  37. }
  38.  
  39. @end


main.m

  1. #import <Foundation/Foundation.h>
  2. #import "Square.h"
  3.  
  4. int main(int argc, const char * argv[]) {
  5. @autoreleasepool {
  6. Square *square = [[Square alloc] init];
  7. [square setSide: 10];
  8. NSLog(@"area: %i, perimeter: %i",
  9. [square area], [square perimeter]);
  10. }
  11. return 0;
  12. }

运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号