使用数组初始化对象
我正在阅读(使用 Squeak)Ron Jeffries 的发现更好的代码:Bowling for Smalltalk 系列我无法通过第三文章。
正在创建一个新类(称为 Frame),它将数组作为构造函数中的参数。
Frame class>>new: anArray
^self new setRolls: anArray
Frame>>setRolls: anArray
rolls := anArray
当我尝试在简单的测试中运行它时:
testFrame
| frame rolls |
rolls := Array with: 5 with: 4.
frame := Frame new: rolls.
出现以下错误:
alt text http://files.getdropbox.com/u/120566/junk/error.png
我应该如何修改 #new 消息以便能够使用数组初始化 Frame 对象?
I was going through (using Squeak) the Discovering Better Code: Bowling for Smalltalk Series by Ron Jeffries and I can't get pass through the third article.
A new class (called Frame) is being created which takes an array as an argument in the constructor.
Frame class>>new: anArray
^self new setRolls: anArray
Frame>>setRolls: anArray
rolls := anArray
When I try to run this in a simple test:
testFrame
| frame rolls |
rolls := Array with: 5 with: 4.
frame := Frame new: rolls.
I get the following error:
alt text http://files.getdropbox.com/u/120566/junk/error.png
How should I modify the #new message to be able to initialize Frame object with an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜您未能将 new: 方法正确添加到 Frame 类中。 你确定你把它放在类端(Frame类)而不是实例端(Frame)? 为此,请在添加新方法之前单击“类”按钮:。
I guess you failed adding the method new: correctly to Frame class. Are you sure you put it on the class side (Frame class) and not on the instance side (Frame)? To do it, click on the 'class' button, before adding your method new:.
你真的不想在这里重写
new:
。new:
传统上保留用于“创建此整数大小的项目”,它对您的影响并不令我感到惊讶。您想要的构造函数类型的更传统名称是
fromArray:
,甚至可能是fromCollection:
,它可能会按照您的意愿工作。You really don't want to override
new:
here.new:
is traditionally reserved for "Create an item of this integer size", and it doesn't surprise me that it's blowing up on you.A more traditional name for the kind of constructor you want is
fromArray:
, or perhaps evenfromCollection:
which would probably have worked as you wished.