无法创建对象实例

时间:2019-05-01 02:23:23

标签: object gnu-smalltalk

我刚刚开始使用gnu-smalltalk。我从here处获取了以下代码来定义一个类:

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
]

我认为通常的方法应使用一个名称和一个或多个参数,如代码here所示:

   spend: amount [
       <category: 'moving money'>
       balance := balance - amount
   ]

1 个答案:

答案 0 :(得分:0)

要创建Complex25 + 25i评估

Complex real: 25 imaginary: 25

我怎么知道?因为问题的第一部分是

Complex class >> real: r imaginary: i [
       <category: 'instance creation'>
       ^(super new) setReal: r setImag: i
   ]

您的错误是写了Complex new: real: 25 imaginary: 25,它不符合Smalltalk语法。

具有2个(或更多)参数的消息的Smalltalk语法由2个(或更多)关键字组成,以冒号结尾,每个关键字后跟相应的参数。

例如,方法setReal: r setImag: i有两个关键字,分别为setReal:setImag:,并接收了两个参数ri。该方法的名称(在Smalltalk中称为选择器)是通过串联关键字(在这种情况下为Symbol)而产生的setReal:setImag: