我才刚开始使用gnu-smalltalk。我从这里获取了下面的代码来定义一个类:
Number subclass: Complex [
| realpart imagpart |
"This is a quick way to define class-side methods."
Complex class >> new [
<category: 'instance creation'>
^self error: 'use real:imaginary:'
]
Complex class >> new: ignore [
<category: 'instance creation'>
^self new
]
Complex class >> real: r imaginary: i [
<category: 'instance creation'>
^(super new) setReal: r setImag: i
]
setReal: r setImag: i [ "What is this method with 2 names?"
<category: 'basic'>
realpart := r.
imagpart := i.
^self
]
]但是,我无法创建该类的任何实例。我尝试过各种方法,下面给出的错误最少!
cn := Complex new: real:15 imaginary:25
cn printNl错误是:
complexNumber.st:24: expected object大多数错误如下所示,例如,如果在new关键字之后没有冒号:
$ gst complexNumber.st
Object: Complex error: use real:imaginary:
Error(Exception)>>signal (ExcHandling.st:254)
Error(Exception)>>signal: (ExcHandling.st:264)
Complex class(Object)>>error: (SysExcept.st:1456)
Complex class>>new (complexNumber.st:7)
UndefinedObject>>executeStatements (complexNumber.st:25)
nil此外,我也不清楚这个有2个名称的方法是什么,每个名称都有一个参数:
setReal: r setImag: i [ "How can there be 2 names and arguments for one method/function?"
<category: 'basic'>
realpart := r.
imagpart := i.
^self
]我认为通常的方法应该只有一个名称和参数,如代码这里:
spend: amount [
<category: 'moving money'>
balance := balance - amount
]发布于 2019-05-01 03:16:19
若要创建Complex编号25 + 25i求值
Complex real: 25 imaginary: 25我怎么知道?因为你问题的第一部分是
Complex class >> real: r imaginary: i [
<category: 'instance creation'>
^(super new) setReal: r setImag: i
]您的错误是编写不符合Smalltalk语法的Complex new: real: 25 imaginary: 25。
带有(比方说)2个(或更多)参数的消息的Smalltalk语法由2个(或更多)关键字组成,以冒号结尾,后面跟着对应的参数。
例如,方法setReal: r setImag: i有两个关键字,即setReal:和setImag:,并接收两个参数r和i。该方法的名称(在Smalltalk中称为它的选择器)是由于连接关键字而产生的Symbol,在本例中是setReal:setImag:。
https://stackoverflow.com/questions/55930915
复制相似问题