面向对象编程中的组合、继承与文件组织
1. 轮胎访问器的实现
轮胎访问器的实现包含两个方法: setTire:atIndex: 和 tireAtIndex: 。以下是具体代码:
- (void) setTire: (Tire *) tire atIndex: (int) index
{
if (index < 0 || index > 3) {
NSLog (@"bad index (%d) in setTire:atIndex:",index);
exit (1);
}
tires[index] = tire;
} // setTire:atIndex:
- (Tire *) tireAtIndex: (int) index
{
if (index < 0 || index > 3) {
NSLog (@"bad index (%d) in tireAtIndex:", index);
exit (1);
}
return (tires[index]);
} // tireAtIndex:
这两个方法都包含了对数组索引有效性的检查,这属于防御性编程。因为 tires 是一个 C 风格的数组,编译器不会对访问数组时使用的索引进行错误检查。如果索引超出了 0 到 3 的范围,程序会打印错误信息并退出。以下是使用这些访问器的代码示例:
超级会员免费看
订阅专栏 解锁全文
1085

被折叠的 条评论
为什么被折叠?



