我刚开始使用 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
]