使用数组初始化对象

发布于 2024-07-25 19:05:11 字数 806 浏览 8 评论 0原文

我正在阅读(使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨洒年华 2024-08-01 19:05:11

我猜您未能将 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:.

调妓 2024-08-01 19:05:11

你真的不想在这里重写 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 even fromCollection: which would probably have worked as you wished.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文