Objective-C类与C宏定义编程实践

22、为 Rectangle 类编写一个名为 draw 的方法,该方法使用破折号和竖线字符绘制一个矩形。当执行以下代码序列:Rectangle *myRect = [[Rectangle alloc] init]; [myRect setWidth: 10 andHeight: 3]; [myRect draw]; [myRect release]; 时,将产生以下输出:

—————
| |
| |
| |
—————
以下是实现该功能的示例代码:

#import <Foundation/Foundation.h>

@interface XYPoint: NSObject
{
    int x;
    int y;
}
@property int x, y;
-(void) setX: (int) xVal andY: (int) yVal;
@end

@implementation XYPoint
@synthesize x, y;
-(void) setX: (int) xVal andY: (int) yVal 
{ 
    x = xVal;
    y = yVal;
}
@end

@interface Rectangle: NSObject
{
    int width;
    int height;
    XYPoint *origin;
}
-(void) setWidth: (int) w andHeight: (int) h;
-(void) draw;
@end

@implementation Rectangle
-(void) setWidth: (int) w andHeight: (int) h 
{ 
    width = w;
    height = h;
}
-(void) draw 
{ 
    for (int i = 0; i < width; i++) 
    { 
        printf("-"); 
    }
    printf("\n"); 
    for (int i = 0; i < height - 2; i++) 
    { 
        printf("|"); 
        for (int j = 0; j < width - 2; j++) 
        { 
            printf(" "); 
        }
        printf("|\n"); 
    }
    for (int i = 0; i < width; i++) 
    { 
        printf("-"); 
    }
    printf("\n");
}
@end

int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool {
        Rectangle *myRect = [[Rectangle alloc] init]; 
        [myRect setWidth: 10 andHeight: 3]; 
        [myRect draw]; 
        [myRect release]; 
    }
    return 0;
}

在上述代码中,定义了 XYPoint 类用于表示矩形的原点, Rectangle 类包含宽度、高度和原点信息。 draw 方法实现了使用破折号和竖线字符绘制矩形的功能。在 main 函数中创建了一个 Rectangle 对象,设置其宽度和高度,调用 draw 方法绘制矩形,最后释放对象。

23、在程序中定义的id类型变量dataValue,能否被赋值为自定义的Rectangle对象?也就是说,语句dataValue = [[Rectangle alloc] init]; 是否有效?为什么?

该语句有效。因为 id 类型变量可存储程序中任何类型的对象,所以能将 Rectangle 对象赋值给 dataValue

24、定义一个XYPoint类,该类包含x和y两个属性。为这个XYPoint类添加一个print方法,使其以(x, y)的格式显示点。然后编写一个程序,创建一个XYPoint对象,设置其值,将其赋值给id类型的变量dataValue,最后显示其值。

首先,定义 XYPoint 类并添加 print 方法。

以下是 XYPoint.h 文件的代码:

#import <Foundation/Foundation.h>

@interface XYPoint : NSObject

@property int x;
@property int y;

-(void)print;

@end

以下是 XYPoint.m 文件的代码:

#import "XYPoint.h"

@implementation XYPoint

-(void)print {
    NSLog("(%d, %d)", self.x, self.y);
}

@end

然后,编写主程序创建 XYPoint 对象,设置其值,赋值给 id 变量 dataValue 并显示其值,示例代码如下:

#
转载请说明出处内容投诉
CSS教程网 » Objective-C类与C宏定义编程实践

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买